https://www.acmicpc.net/problem/16946
ํ์ด
1. ๋ฒฝ์ผ๋ก ๋๋ ์ง ๊ตฌ์ญ๋ค์ ๋ฒํธ๋ฅผ ๋งค๊น (๋์์ ๊ฐ ๊ตฌ์ญ์ ์นธ ์๋ ์ ์ฅํด๋ )
2. ํน์ ์นธ์ ๋ฒฝ์ ์์ค๋ค๋ฉด ์ด๋ค ๊ตฌ์ญ๋ค์ด ์ฐ๊ฒฐ๋๋์ง ๋ณด๊ณ 1๋ฒ์์ ๊ตฌํด๋ ์นธ ์ ์ ๋ณด๋ฅผ ํ์ฉํด์ ์ฐ๊ฒฐ๋๋ ์นธ ์ ๊ตฌํ๊ธฐ
์๋ฅผ๋ค์ด, X๊ฐ ๋ฒฝ์ด๋ผ๊ณ ์น๋ฉด, ๋ค์๊ณผ ๊ฐ์ด ๋๋ ์ง ๊ตฌ์ญ์ ๋ฒํธ๋ฅผ ๋งค๊ธฐ๊ณ
XX00X XX11X
00XXX => 22XXX
0X0X0 2X3X4
X0X0X X5X6X
๋ฐฐ์ด์ ๊ฐ ๊ตฌ์ญ์ ์นธ ์๋ฅผ ์ ์ฅํด๋๊ธฐ.
[2, 3, 1, 1, 1, 1]
1๋ฒ ๊ณผ์ ์ BFS (flood-fill)์ ์ฌ์ฉํ๊ณ , 2๋ฒ ๊ณผ์ ์ ๊ทธ๋ฅ ๋ฒฝ์ด ์๋ ์นธ์ ์ํ์ข์ฐ๋ง ํ์ธํด์ฃผ๋ฉด ๋จ.
์ฝ๋
๋๋ณด๊ธฐ
import java.io.*;
import java.util.*;
public class Main {
public static class Pos {
public int row, col;
public Pos(int r, int c) {
row = r;
col = c;
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int R = Integer.parseInt(st.nextToken());
int C = Integer.parseInt(st.nextToken());
boolean[][] wall = new boolean[R][C];
for (int r = 0; r < R; r++) {
for (int c = 0; c < C; c++) {
wall[r][c] = (br.read() == '1');
}
br.readLine();
}
int[][] map = new int[R][C];
int areaNum = 0;
int[] areaSize = new int[R * C + 1];
int[] dirR = { -1, 1, 0, 0 };
int[] dirC = { 0, 0, -1, 1 };
for (int r = 0; r < R; r++) {
for (int c = 0; c < C; c++) {
if (map[r][c] == 0 && !wall[r][c]) {
areaNum++;
areaSize[areaNum] = 1;
Queue<Pos> que = new LinkedList<>();
que.add(new Pos(r, c));
map[r][c] = areaNum;
while (!que.isEmpty()) {
Pos cur = que.remove();
for (int dir = 0; dir < 4; dir++) {
int row = cur.row + dirR[dir];
int col = cur.col + dirC[dir];
if (row < 0 || row >= R || col < 0 || col >= C) {
continue;
}
if (wall[row][col] || map[row][col] > 0) {
continue;
}
map[row][col] = areaNum;
areaSize[areaNum]++;
que.add(new Pos(row, col));
}
}
}
}
}
boolean[] checked = new boolean[areaNum + 1];
int[][] answer = new int[R][C];
for (int r = 0; r < R; r++) {
for (int c = 0; c < C; c++) {
if (wall[r][c]) {
answer[r][c] = 1;
for (int dir = 0; dir < 4; dir++) {
int row = r + dirR[dir];
int col = c + dirC[dir];
if (row < 0 || row >= R || col < 0 || col >= C) {
continue;
}
if (checked[map[row][col]]) {
continue;
}
answer[r][c] += areaSize[map[row][col]];
checked[map[row][col]] = true;
}
for (int dir = 0; dir < 4; dir++) {
int row = r + dirR[dir];
int col = c + dirC[dir];
if (row < 0 || row >= R || col < 0 || col >= C) {
continue;
}
checked[map[row][col]] = false;
}
}
}
}
StringBuilder sb = new StringBuilder();
for (int r = 0; r < R; r++) {
for (int c = 0; c < C; c++) {
sb.append(answer[r][c] % 10);
}
sb.append('\n');
}
System.out.println(sb);
br.close();
}
}
'Problem Solving' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Java] ๋ฐฑ์ค 1724 - ๊ทธ๋ฆผํ (0) | 2024.03.13 |
---|---|
[Java] ๋ฐฑ์ค 1999 - ์ต๋์ต์ (0) | 2024.03.01 |
[Java] ๋ฐฑ์ค 31091 - ๊ฑฐ์ง๋ง (0) | 2024.02.23 |
[Java] ๋ฐฑ์ค 31423 - ์ ์ด ํตํํฉ ๊ณํ (0) | 2024.02.21 |
[Java] ๋ฐฑ์ค 31248 - 3+1 ํ๋ ธ์ด ํ (0) | 2024.02.01 |