fork download
  1. import java.util.*;
  2. import java.io.*;
  3.  
  4. public class Main{
  5. public static void main(String[] args) throws IOException {
  6. StringTokenizer st = new StringTokenizer(br.readLine());
  7. int n = Integer.parseInt(st.nextToken());
  8. int m = Integer.parseInt(st.nextToken());
  9.  
  10. int[][] arr = new int[n][m];
  11. for (int i = 0; i < n; i++) {
  12. st = new StringTokenizer(br.readLine());
  13. for (int j = 0; j < m; j++) {
  14. arr[i][j] = Integer.parseInt(st.nextToken());
  15. }
  16. }
  17.  
  18. // 동서남북배열
  19. int[] bx = {1, 0, -1, 0};
  20. int[] by = {0, 1, 0, -1};
  21.  
  22. int pictureN = 0;
  23. int biggest = 0;
  24.  
  25. while (true) {
  26. Pair startPos = null;
  27. boolean foundPicture = false;
  28. for (int i = 0; i < n; i++) {
  29. for (int j = 0; j < m; j++) {
  30. if (arr[i][j] == 1) {
  31. startPos = new Pair(i, j);
  32. foundPicture = true;
  33. break;
  34. }
  35. }
  36. if (foundPicture) {
  37. break;
  38. }
  39. }
  40. if (!foundPicture){
  41. break;
  42. }
  43. pictureN++;
  44.  
  45. Queue<Pair> queue = new LinkedList<>();
  46. int thisSize = 0;
  47. // 첫번째주입
  48. arr[startPos.x][startPos.y] = 0;
  49. queue.add(startPos);
  50. thisSize++;
  51.  
  52. // while(!empty)
  53. // queue.pop
  54. // for(동서남북)
  55. // if(boundary exception check)
  56. // if(방문했던곳 or 벽인지)
  57. // 체크 & push
  58. while (!queue.isEmpty()) {
  59. Pair nowPos = queue.poll();
  60. for (int i = 0; i < 4; i++) {
  61. int px = nowPos.x + bx[i];
  62. int py = nowPos.y + by[i];
  63.  
  64. if (px < 0 || px > n - 1 || py < 0 || py > m - 1) {
  65. continue;
  66. }
  67. if (arr[px][py] == 1) {
  68. queue.add(new Pair(px, py));
  69. arr[px][py] = 0;
  70. thisSize++;
  71. }
  72. }
  73. }
  74.  
  75. if (thisSize > biggest) {
  76. biggest = thisSize;
  77. }
  78. }
  79. System.out.println(pictureN);
  80. System.out.println(biggest);
  81. }
  82.  
  83. static class Pair{
  84. int x;
  85. int y;
  86.  
  87. public Pair(int x, int y) {
  88. this.x = x;
  89. this.y = y;
  90. }
  91. }
  92. }
Runtime error #stdin #stdout #stderr 0.07s 52940KB
stdin
4 4
1111
1001
1001
1111
stdout
Standard output is empty
stderr
Exception in thread "main" java.util.NoSuchElementException
	at java.base/java.util.StringTokenizer.nextToken(StringTokenizer.java:349)
	at Main.main(Main.java:15)