아이디어
섬이 존재하는 좌표에서 dfs 를 수행해서 같은 섬(걸어갈 수 있는 좌표)을 탐색하면 1개의 섬의 땅을 모두 탐색할 수 있다.
이미 탐색한 섬은 다시 탐색하지 않도록 해서 모든 좌표에 대해 위의 방법을 적용하면 총 몇 개의 섬이 존재하는지 알 수 있다.
다만 이 문제에서 '걸어갈 수 있는 경로'는 상,하,좌,우 뿐만 아니라 대각선 방향으로 1칸씩 이동하는 것도 포함하므로 이 점을 생각하고 문제를 풀어야한다.
풀이코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static int[][] map;
static int w;
static int h;
static int[] dx = {-1, 1, 0, 0, 1, 1, -1, -1};
static int[] dy = {0, 0, -1, 1, 1, -1, 1, -1};
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder results = new StringBuilder();
while (true) {
StringTokenizer st = new StringTokenizer(br.readLine());
w = Integer.parseInt(st.nextToken());
h = Integer.parseInt(st.nextToken());
if (w == 0 && h == 0) break;
map = new int[h][w];
for (int i = 0; i < h; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < w; j++) {
map[i][j] = Integer.parseInt(st.nextToken());
}
}
int result = 0;
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
if (map[i][j] == 1) {
dfs(i, j);
result++;
}
}
}
results.append(result).append("\n");
}
System.out.println(results);
}
public static void dfs(int i, int j) {
map[i][j] = 0;
for (int k = 0; k < 8; k++) {
int x = i + dx[k];
int y = j + dy[k];
if (x < 0 || y < 0 || x >= h || y >= w || map[x][y] != 1) continue;
dfs(x, y);
}
}
}
'Algorithm > 백준 알고리즘' 카테고리의 다른 글
1455번. 뒤집기 Ⅱ (0) | 2023.11.01 |
---|---|
15990번. 1, 2, 3 더하기 5 (0) | 2023.10.31 |
14400번. 편의점 2 (1) | 2023.10.31 |
1753번. 최단경로 (0) | 2023.10.29 |
9663번. N-Queen (1) | 2023.10.29 |