▶코드
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 N, M, cnt;
static LinkedList<Integer> result;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
range = new int[N][M];
visited = new boolean[N][M];
result = new LinkedList<>();
cnt = 1;
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < M; j++) {
range[i][j] = Integer.parseInt(st.nextToken());
}
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (!visited[i][j] && range[i][j] == 1) {
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 < N && ny < M && !visited[nx][ny] && range[nx][ny] == 1) {
dfs(nx, ny);
cnt++;
}
}
}
}
'알고리즘 > 백준 풀이(탐색)' 카테고리의 다른 글
백준 3184번 - 양(DFS) (0) | 2024.05.07 |
---|---|
백준 1303번 - 전쟁 - 전투(DFS) (0) | 2024.04.24 |
백준 1743번 - 음식물 피하기 (0) | 2024.04.23 |
백준 2583번 - 영역 구하기(DFS) (0) | 2024.04.21 |
백준 4963번 - 섬의 개수(DFS) (1) | 2024.04.20 |