▶코드
import java.util.*;
import java.io.*;
public class Main {
static int range[][];
static boolean visited[][];
static int dx[] = {0, 0, -1, 1, -1, -1, 1, 1};
static int dy[] = {-1, 1, 0, 0, -1, 1, -1, 1};
static int W, H;
static int cnt;
static LinkedList<Integer> result;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
cnt = 1;
while (true) {
st = new StringTokenizer(br.readLine());
W = Integer.parseInt(st.nextToken());
H = Integer.parseInt(st.nextToken());
if (W == 0 && H == 0)
break;
range = new int[H][W];
visited = new boolean[H][W];
result = new LinkedList<>();
for (int i = 0; i < H; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < W; j++) {
range[i][j] = Integer.parseInt(st.nextToken());
}
}
for (int i = 0; i < H; i++) {
for (int j = 0; j < W; j++) {
if (range[i][j] == 1 && !visited[i][j]) {
dfs(i, j);
result.add(cnt);
cnt = 1;
}
}
}
System.out.println(result.size());
}
}
public static void dfs(int x, int y) {
visited[x][y] = true;
for (int i = 0; i < 8; i++) {
int nx = dx[i] + x;
int ny = dy[i] + y;
if (nx >= 0 && ny >= 0 && nx < H && ny < W && !visited[nx][ny] && range[nx][ny] == 1) {
dfs(nx, ny);
cnt++;
}
}
}
}
'알고리즘 > 백준 풀이(탐색)' 카테고리의 다른 글
백준 1743번 - 음식물 피하기 (0) | 2024.04.23 |
---|---|
백준 2583번 - 영역 구하기(DFS) (0) | 2024.04.21 |
백준 11725번 - 트리의 부모 찾기(DFS) (0) | 2024.04.20 |
백준 2468번 - 안전 영역(DFS) (1) | 2024.04.20 |
백준 10026번 - 적록색약(DFS) (1) | 2024.04.20 |