BOJ_S2_4963
π [S2_4963] μ¬μ κ°μ
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static StringTokenizer st;
static int[][] arr;
static int w, h;
static boolean[][] v;
static int[] dx = {-1, -1, -1, 0, 1, 1, 1, 0};
static int[] dy = {-1, 0, 1, 1, 1, 0, -1, -1};
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
while (true) {
st = new StringTokenizer(br.readLine(), " ");
// λλΉ w, λμ΄ h
w = Integer.parseInt(st.nextToken());
h = Integer.parseInt(st.nextToken());
if (w == 0 && h == 0) {
break;
}
// μ§λ
arr = new int[h][w];
// μ¬μΈμ§ μλμ§ check
v = new boolean[h][w];
// μ¬μ κ°μ
int cnt = 0;
// μ§λ μ
λ ₯
for (int i = 0; i < h; i++) {
st = new StringTokenizer(br.readLine(), " ");
for (int j = 0; j < w; j++) {
arr[i][j] = Integer.parseInt(st.nextToken());
}
}
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
if (arr[i][j] == 1 && !v[i][j]) {
dfs(j, i);
cnt++;
}
}
}
sb.append(cnt).append("\n");
}
System.out.println(sb);
}
static void dfs(int x, int y) {
v[y][x] = true;
int nx, ny;
for (int z = 0; z < 8; z++) {
nx = x + dx[z];
ny = y + dy[z];
if (nx < 0 || ny < 0 || nx >= w || ny >= h) {
continue;
} else if (arr[ny][nx] == 1 && !v[ny][nx]) {
dfs(nx, ny);
}
}
}
}
π€ λμ μκ°
μ¬μ΄ κ°λ‘,μΈλ‘,λκ°μ κΉμ§ μ°κ²°μ΄ λ μ μμ΄μ 8λ°©ν₯ νμμ μ¬μ©νλ€.
κ·Έλ¦¬κ³ κΉμ΄ μ°μ νμμ μ΄μ©νμ¬ μ°κ²°λμλ κ³³λ€μ νμ
νλ€.
dfs()λ₯Ό νλ² λ€ μ€νν΄μ£Όλ©΄ μΉ΄μ΄ν
μ ν΄μ£Όμ΄ μ΄ μ¬μ κ°μλ₯Ό ꡬν΄μ£Όμλ€.
λ°©ν₯ νμκ³Ό dfs()λ₯Ό μ μκ³ μλ€λ©΄ κ°λ¨νκ² νλ Έμ λ¬Έμ μ΄λ€.