Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class Main {
- public static final int[] dx = {0,0,1,-1,1,1,-1,-1};
- public static final int[] dy = {1,-1,0,0,1,-1,1,-1};
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- while(true){
- //주의할 부분 n : 너비, m : 높이
- int m = sc.nextInt();
- int n = sc.nextInt();
- if(n == 0 && m == 0){
- break;
- }
- int[][] a = new int[n][m];
- for(int i = 0; i < n; i++) {
- for(int j = 0; j < m; j++) {
- a[i][j] = sc.nextInt();
- }
- }
- int cnt = 0;
- int[][] b = new int[n][m];
- for (int i=0; i<n; i++) {
- for (int j=0; j<m; j++) {
- if (a[i][j] == 1 && b[i][j] == 0) {
- dfs(a, b, i, j, n, m, ++cnt);
- }
- }
- }
- System.out.println(cnt);
- }
- }
- public static void dfs(int[][] a, int[][] b, int x, int y, int n, int m, int cnt) {
- b[x][y] = cnt;
- for(int i = 0; i < 8; i++) {
- int nx = x + dx[i];
- int ny = y + dy[i];
- if(nx >= 0 && ny >= 0 && nx < n && ny < m) {
- if(a[nx][ny] == 1 && b[nx][ny] == 0) {
- dfs(a,b,nx,ny,n,m,cnt);
- }
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment