π [λ°±μ€μκ³ λ¦¬μ¦ νμ΄] Q.4963 μ¬μ κ°μ λ¬Έμ νμ΄
π λ¬Έμ
https://www.acmicpc.net/problem/4963
μ μ¬κ°νμΌλ‘ μ΄λ£¨μ΄μ Έ μλ μ¬κ³Ό λ°λ€ μ§λκ° μ£Όμ΄μ§λ€. μ¬μ κ°μλ₯Ό μΈλ νλ‘κ·Έλ¨μ μμ±νμμ€.
ν μ μ¬κ°νκ³Ό κ°λ‘, μΈλ‘ λλ λκ°μ μΌλ‘ μ°κ²°λμ΄ μλ μ¬κ°νμ κ±Έμ΄κ° μ μλ μ¬κ°νμ΄λ€.
λ μ μ¬κ°νμ΄ κ°μ μ¬μ μμΌλ €λ©΄, ν μ μ¬κ°νμμ λ€λ₯Έ μ μ¬κ°νμΌλ‘ κ±Έμ΄μ κ° μ μλ κ²½λ‘κ° μμ΄μΌ νλ€.
μ§λλ λ°λ€λ‘ λλ¬μΈμ¬ μμΌλ©°, μ§λ λ°μΌλ‘ λκ° μ μλ€.
π μ κ·Όλ²
μ¬μ κ°μ λ¬Έμ μ
λλ€.
dfs λ bfs νμμ ν΅ν΄ λͺκ°μ κ·Έλν(μ¬)κ° μλμ§
μ
μκ° μμ΅λλ€.
π» μ½λ
package problem.bfsdfs;
import java.util.*;
public class Main_4963 {
static int count;
static int w;
static int h;
static boolean[][] visited;
static int[][] island;
static int moveX[] = {0, 0, -1, 1, 1, 1, -1, -1};
static int moveY[] = {-1, 1, 0, 0, -1, 1, -1, 1};
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
w = sc.nextInt();
h = sc.nextInt();
if (w == 0 && h == 0)
break;
island = new int[h][w];
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
island[i][j] = sc.nextInt();
}
}
count = 0;
visited = new boolean[h][w];
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
if (island[i][j] == 1 && visited[i][j] == false)
dfs(i, j, ++count);
}
}
System.out.println(count);
}
sc.close();
}
public static void dfs(int x, int y, int count) {
visited[x][y] = true;
for (int i = 0; i < moveX.length; i++) {
int nx = x + moveX[i];
int ny = y + moveY[i];
if (0 <= nx && nx < h && 0 <= ny && ny < w) {
if (island[nx][ny] == 1 && visited[nx][ny] == false) {
dfs(nx, ny, count);
}
}
}
}
}
Written on July 14, 2020