PS/๋ฐฑ์ค
[๋ฐฑ์ค] 2667 : ๋จ์ง๋ฒํธ๋ถ์ด๊ธฐ - java [์๋ฐ]
mokhs
2022. 2. 28. 18:32
https://www.acmicpc.net/problem/2667
2667๋ฒ: ๋จ์ง๋ฒํธ๋ถ์ด๊ธฐ
<๊ทธ๋ฆผ 1>๊ณผ ๊ฐ์ด ์ ์ฌ๊ฐํ ๋ชจ์์ ์ง๋๊ฐ ์๋ค. 1์ ์ง์ด ์๋ ๊ณณ์, 0์ ์ง์ด ์๋ ๊ณณ์ ๋ํ๋ธ๋ค. ์ฒ ์๋ ์ด ์ง๋๋ฅผ ๊ฐ์ง๊ณ ์ฐ๊ฒฐ๋ ์ง์ ๋ชจ์์ธ ๋จ์ง๋ฅผ ์ ์ํ๊ณ , ๋จ์ง์ ๋ฒํธ๋ฅผ ๋ถ์ด๋ ค ํ๋ค. ์ฌ
www.acmicpc.net
์ดํด
- ํด๋น ๋ฌธ์ ๋ 2์ฐจ์ ๋ฐฐ์ด๋ก ์ฃผ์ด์ง๋ map์ ํ์ํ์ฌ ์ฐ๊ฒฐ๋ ์ง์ญ์ ์ฐพ๋ ๋ฌธ์ ์ด๋ค.
- ์ฆ map์ ์ํํ๋ฉฐ ๋ฐฉ๋ฌธ์ฒ๋ฆฌ๋์ง ์์ ์ขํ๊ฐ ์๋ค๋ฉด ํด๋น ์ขํ๋ฅผ ๊ธฐ์ค์ผ๋ก ์ธ์ ํ ์ขํ๋ฅผ ๋ชจ๋ ๋ฐฉ๋ฌธ์ฒ๋ฆฌํ๋ค.
- ์ด๋ ๊ฒํ๋ฉด ์ฐ๊ฒฐ๋ ์ง์ญ์ ๋ชจ๋ ๋ฐฉ๋ฌธ์ฒ๋ฆฌ๋ ๊ฒ์ด๊ณ map์ ์ํ ์ค์ ๋ฐฉ๋ฌธ๋์ง ์์ ์ขํ๋ฅผ ์ฐพ๋๋ค๋ฉด ์๋ก์ด ์ง์ญ์ ๋ฐ๊ฒฌ์ ์๋ฏธํ๋ค.
- ๋ฐ๋ผ์ map์ ์ํํ๋ฉฐ ๋ฐฉ๋ฌธ๋์ง ์์ ์ขํ๋ฅผ ์ฐพ์ ์ ํด๋น ์ขํ๋ฅผ ์์์ผ๋ก ์ฃผ๋ณ์ ํ์ํ๊ณ , ์ฃผ๋ณ์ ๋ฐฉ๋ฌธ์ฒ๋ฆฌ๋์ง ์์ ์ขํ์ ์๋ฅผ ๊ธฐ๋กํ๋ฉด ๋๋ค.

ํ์ด
- map์ ์ํํ๋ฉฐ ๋ฐฉ๋ฌธ๋์ง ์์ ์ขํ๋ฅผ ์ฐพ์ ์ ํด๋น ์ขํ๋ฅผ ์์์ผ๋ก ์ฃผ๋ณ์ ํ์ํ๋ค.
- ์ฃผ๋ณ์ ํ์ํ๋ฉฐ, ๋ฐฉ๋ฌธ๋์ง ์์ ์ขํ์ธ ๊ฒฝ์ฐ ๋ฐฉ๋ฌธ์ฒ๋ฆฌํ๊ณ , ๊ฐ์๋ฅผ 1 count ํ๋ค. (outBound ์์ธ์ ์ฃผ์ํ์)
- ์ฌ๊ทํจ์๋ฅผ ์ด์ฉํด ํ์ํ๋ฉฐ, ํ์ ์ข ๋ฃ ์ ํด๋น ํ์์์ ๋ฐ๊ฒฌํ ์ง ์๋ฅผ ๊ธฐ๋กํ๋ค.
- ์ฌ๊ธฐ์๋ ์ฐ์ ์์ ํ์ ํด๋น ๊ตฌ์ญ์ ์ง ์๋ฅผ ๊ธฐ๋กํด์ ์ ๋ต์ ์ถ๋ ฅํ๋ค.
์ฝ๋
import java.io.*;
import java.util.PriorityQueue;
public class ๋จ์ง๋ฒํธ๋ถ์ด๊ธฐ_2667 {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
static int N;
static int[][] map;
public static void main(String[] args) throws IOException {
N = Integer.parseInt(br.readLine());
StringBuilder resultStringBuilder = new StringBuilder();
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();
map = new int[N][N];
for (int y = 0; y < N; y++) {
String[] split = br.readLine().split("");
for (int x = 0; x < split.length; x++) {
map[y][x] = Integer.parseInt(split[x]);
}
}
for (int y = 0; y < N; y++) {
for (int x = 0; x < N; x++) {
if (map[y][x] == 1) {
priorityQueue.add(bfs(x, y));
}
}
}
resultStringBuilder.append(priorityQueue.size() + "\n");
while (!priorityQueue.isEmpty()) {
resultStringBuilder.append(priorityQueue.poll() + "\n");
}
bw.write(resultStringBuilder.toString());
bw.close();
br.close();
}
static int bfs(int x, int y) {
boolean isOutBound = x < 0 || y < 0 || x >= N || y >= N;
if (isOutBound) {
return 0;
}
boolean isVisited = map[y][x] == 0;
if (isVisited) {
return 0;
}
map[y][x] = 0;
return 1 + bfs(x + 1, y) + bfs(x - 1, y) + bfs(x, y + 1) + bfs(x, y - 1);
}
}