728x90
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
import java.io.*;
import java.util.*;
public class Main {
static int w,h;
static int ad[][];
static boolean visit[][];
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
while(true){
int island = 0;
st = new StringTokenizer(br.readLine());
w = Integer.parseInt(st.nextToken());
h = Integer.parseInt(st.nextToken());
if(w == 0 && h == 0) break;
ad = new int[h][w];
visit = new boolean[h][w];
for(int i = 0; i < h; i++){
st = new StringTokenizer(br.readLine());
for(int j = 0; j < w; j++){
ad[i][j] = Integer.parseInt(st.nextToken());
}
}
for(int i = 0; i < h; i++){
for(int j = 0; j < w; j++){
if(ad[i][j] == 1 && !visit[i][j]){
bfs(i,j);
island++;
}
}
}
System.out.println(island);
}
}
static void bfs(int x, int y){
int dx[] = {-1,-1,-1,0,0,1,1,1};
int dy[] = {1,-1,0,1,-1,1,-1,0};
Queue<Integer> q = new LinkedList<>();
q.offer(x);
q.offer(y);
visit[x][y] = true;
while(!q.isEmpty()){
x = q.poll();
y = q.poll();
for(int i = 0; i < 8; i++){
int X = x + dx[i];
int Y = y + dy[i];
if(isRangeTrue(X, Y) && ad[X][Y] == 1 && !visit[X][Y]){
q.offer(X);
q.offer(Y);
visit[X][Y] = true;
}
}
}
}
static boolean isRangeTrue(int x, int y){
return x >= 0 && x < h && y >= 0 && y < w;
}
}
|
cs |
728x90
'BOJ(Java)' 카테고리의 다른 글
자바(백준) 11724 연결 요소의 개수 (0) | 2020.12.30 |
---|---|
자바(백준) 7562 나이트의 이동 (0) | 2020.12.30 |
자바(백준) 3184 양 (0) | 2020.12.30 |
자바(백준) 2644 촌수계산 (0) | 2020.12.29 |
자바(백준) 1260 DFS와 BFS (0) | 2020.11.12 |