Guest User

Untitled

a guest
Apr 20th, 2018
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class Main {
  4.  
  5. public static final int[] dx = {0,0,1,-1,1,1,-1,-1};
  6. public static final int[] dy = {1,-1,0,0,1,-1,1,-1};
  7.  
  8. public static void main(String[] args) {
  9. Scanner sc = new Scanner(System.in);
  10. while(true){
  11. //주의할 부분 n : 너비, m : 높이
  12. int m = sc.nextInt();
  13. int n = sc.nextInt();
  14. if(n == 0 && m == 0){
  15. break;
  16. }
  17. int[][] a = new int[n][m];
  18.  
  19. for(int i = 0; i < n; i++) {
  20. for(int j = 0; j < m; j++) {
  21. a[i][j] = sc.nextInt();
  22. }
  23. }
  24. int cnt = 0;
  25. int[][] b = new int[n][m];
  26. for (int i=0; i<n; i++) {
  27. for (int j=0; j<m; j++) {
  28. if (a[i][j] == 1 && b[i][j] == 0) {
  29. dfs(a, b, i, j, n, m, ++cnt);
  30. }
  31. }
  32. }
  33. System.out.println(cnt);
  34. }
  35. }
  36.  
  37. public static void dfs(int[][] a, int[][] b, int x, int y, int n, int m, int cnt) {
  38. b[x][y] = cnt;
  39. for(int i = 0; i < 8; i++) {
  40. int nx = x + dx[i];
  41. int ny = y + dy[i];
  42. if(nx >= 0 && ny >= 0 && nx < n && ny < m) {
  43. if(a[nx][ny] == 1 && b[nx][ny] == 0) {
  44. dfs(a,b,nx,ny,n,m,cnt);
  45. }
  46. }
  47. }
  48. }
  49. }
Add Comment
Please, Sign In to add comment