๋ฌธ์
ํด๋น ํฌ์คํ ์ ๋ฐฑ์ค์ 2583๋ฒ ์์ญ ๊ตฌํ๊ธฐ ์ ์ ๊ทผ๊ณผ ํด๊ฒฐ ๋ฐฉ๋ฒ์ ์ค๋ช ํ ๊ธ ์ ๋๋ค.
์ ๋ต ์์ค ์ฝ๋๋ฅผ ํ์ธํ์๋ ค๋ฉด solve url ์์ ํ์ธ ๊ฐ๋ฅํฉ๋๋ค.
2583๋ฒ: ์์ญ ๊ตฌํ๊ธฐ
์ฒซ์งธ ์ค์ M๊ณผ N, ๊ทธ๋ฆฌ๊ณ K๊ฐ ๋น์นธ์ ์ฌ์ด์ ๋๊ณ ์ฐจ๋ก๋ก ์ฃผ์ด์ง๋ค. M, N, K๋ ๋ชจ๋ 100 ์ดํ์ ์์ฐ์์ด๋ค. ๋์งธ ์ค๋ถํฐ K๊ฐ์ ์ค์๋ ํ ์ค์ ํ๋์ฉ ์ง์ฌ๊ฐํ์ ์ผ์ชฝ ์๋ ๊ผญ์ง์ ์ x, y์ขํ๊ฐ๊ณผ ์ค
www.acmicpc.net
์ด ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๊ธฐ ์ํด ์ด๋ค ๋ฐฉ์์ผ๋ก ์ ๊ทผํด์ผ ํ๋์ง๋ฅผ ๋จผ์ ์๊ฐํด๋ณด์.
๋ฌธ์ ์ ๊ทผ
์ด๋ฒ ๋ฌธ์ ๋ BFS ๋ DFS ๋ชจ๋ ํ ์ ์๋ ๋ฌธ์ ์ด๋ค.
์ฌ๊ธฐ์ ์ด ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๊ธฐ ์ํ ์ค์ํ ํ์ ๋ชจ๋ ์ข ์ด๋ฅผ ์ด๋ป๊ฒ ๋ฐ๋ผ๋ณผ ๊ฒ์ด๋? ์๋๊ฒ ๊ฐ๋ค.
๋ง์ฝ ๋ฐฐ์ด๋ก ์๊ฐ์ ํ๋ค๋ฉด ๋ชจ๋ ์ข ์ด๋ฅผ 2๊ฐ์ง ๊ด์ ? ์ผ๋ก ๋ฐ๋ผ๋ณผ ์ ์๋ค.
- ๊ฐ๊ฐ ๊ผญ์ง์ ์ ์ขํ๋ก ๋ณผ ๊ฒ์ธ๊ฐ?
- ํ๋์ ์ฌ๊ฐํ์ ์ขํ๋ก ๋ณผ ๊ฒ์ธ๊ฐ?
์ด๋ฒ ๋ฌธ์ ๋ ํ๋์ ์ขํ๋ ๋์ด๊ฐ 1์ธ ์ ์ฌ๊ฐํ ์ผ๋ก ์ทจ๊ธํ๋ฏ๋ก 2๋ฒ ์จฐ ๊ด์ ์ผ๋ก ๋ณด๋ ๊ฒ์ด ๋งค์ฐ ํธํ ๊ฒ์ด๋ค.
์ ๋ต ์ฝ๋
public class Main {
private static int m;
private static int n;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String[] mnk = br.readLine().split(" ");
m = Integer.parseInt(mnk[0]); // y
n = Integer.parseInt(mnk[1]); // x
int k = Integer.parseInt(mnk[2]); // ๊ฐ์
boolean[][] arr = new boolean[m][n];
for (int i = 0; i < k; i++) {
String[] s = br.readLine().split(" ");
int fromX = Integer.parseInt(s[0]);
int fromY = Integer.parseInt(s[1]);
int toX = Integer.parseInt(s[2]);
int toY = Integer.parseInt(s[3]);
mark(arr, fromX, fromY, toX, toY); // ์์น
}
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if(!arr[i][j]) {
list.add(getConnectedComponent(arr, j, i));
}
}
}
Collections.sort(list);
bw.write(list.size() + "\n");
for(int value : list) {
bw.write(value + " ");
}
bw.flush();
bw.close();
}
private static void mark(boolean[][] arr, int fromX, int fromY, int toX, int toY) {
for (int i = fromY; i < toY; i++) {
for (int j = fromX; j < toX; j++) {
arr[i][j] = true;
}
}
}
private static int getConnectedComponent(boolean[][] arr, int x, int y) {
int[] xPos = {1, -1, 0, 0};
int[] yPos = {0, 0, 1, -1};
Queue<Position> queue = new LinkedList<>();
queue.add(new Position(x, y));
arr[y][x] = true;
int count = 1;
while(!queue.isEmpty()) {
Position front = queue.remove();
for (int i = 0; i < 4; i++) {
int xx = front.x + xPos[i];
int yy = front.y + yPos[i];
if(0 <= xx && xx < n && 0 <= yy && yy < m) {
if(!arr[yy][xx]) {
arr[yy][xx] = true;
queue.add(new Position(xx, yy));
count++;
}
}
}
}
return count;
}
private static class Position {
int x;
int y;
Position(int x, int y) {
this.x = x;
this.y = y;
}
}
}
๋๊ธ