|
| 1 | +import java.io.BufferedReader; |
| 2 | +import java.io.InputStreamReader; |
| 3 | +import java.io.IOException; |
| 4 | +import java.util.Collection; |
| 5 | +import java.util.Collections; |
| 6 | +import java.util.LinkedList; |
| 7 | +import java.util.PriorityQueue; |
| 8 | +import java.util.Queue; |
| 9 | +import java.util.StringTokenizer; |
| 10 | + |
| 11 | +public class Main { |
| 12 | + static int arr[][]; |
| 13 | + static int dx[] = {-1,-1,-1,0,0,1,1,1}; |
| 14 | + static int dy[] = {-1,0,1,-1,1,-1,1,0}; |
| 15 | + static boolean[][] visited; |
| 16 | + static int w,h; |
| 17 | + |
| 18 | + public static void main(String[] args) throws IOException { |
| 19 | + |
| 20 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 21 | + StringTokenizer st; |
| 22 | + |
| 23 | + StringBuilder sb = new StringBuilder(); |
| 24 | + while(true) { |
| 25 | + st = new StringTokenizer(br.readLine()); |
| 26 | + w = Integer.parseInt(st.nextToken()); |
| 27 | + h = Integer.parseInt(st.nextToken()); |
| 28 | + |
| 29 | + if(w==0 && h==0) |
| 30 | + break; |
| 31 | + |
| 32 | + |
| 33 | + arr = new int[h][w]; |
| 34 | + visited = new boolean[h][w]; |
| 35 | + |
| 36 | + |
| 37 | + for(int i =0; i<h; i++) { |
| 38 | + st = new StringTokenizer(br.readLine()); |
| 39 | + for(int j =0; j<w; j++) { |
| 40 | + arr[i][j] = Integer.parseInt(st.nextToken()); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + int count =0; |
| 45 | + |
| 46 | + for(int i =0; i<h; i++) { |
| 47 | + for(int j =0; j<w; j++) { |
| 48 | + if(visited[i][j] == false && arr[i][j]== 1) { |
| 49 | + bfs(i,j); |
| 50 | + count++; |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + sb.append(count).append("\n"); |
| 55 | + } |
| 56 | + System.out.println(sb); |
| 57 | + |
| 58 | + } |
| 59 | + static void bfs(int x, int y) { |
| 60 | + |
| 61 | + Queue<int[]> queue = new LinkedList<>(); |
| 62 | + |
| 63 | + queue.add(new int[]{x,y}); |
| 64 | + visited[x][y]= true; |
| 65 | + |
| 66 | + while(!queue.isEmpty()) { |
| 67 | + int now[] = queue.poll(); |
| 68 | + |
| 69 | + int nowx = now[0]; |
| 70 | + int nowy = now[1]; |
| 71 | + |
| 72 | + for(int i =0; i<8; i++) { |
| 73 | + int nx = nowx + dx[i]; |
| 74 | + int ny = nowy + dy[i]; |
| 75 | + if(nx >=0 && nx <h && ny >=0 && ny <w && arr[nx][ny] == 1) { |
| 76 | + if(visited[nx][ny] == false) { |
| 77 | + queue.add(new int[]{nx,ny}); |
| 78 | + visited[nx][ny] =true; |
| 79 | + } |
| 80 | + } |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + } |
| 85 | +} |
0 commit comments