fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. { public static int[] dr = {1,1,0,-1,-1,-1,0,1};
  10. public static int[] dc = {0,1,1,1,0,-1,-1,-1};
  11. public static int floodFill(int row, int column, int one, int zero, int size, int[][] grid) {
  12. if (row < 0 || row>= size || column < 0 || column >= size ) {
  13. return 0;
  14. }
  15. if(grid[row][column] != one) {
  16. return 0;
  17. }
  18. int answer = 1;
  19. grid[row][column] = zero;
  20. for (int d = 0; d < 8; d++) {
  21. answer += floodFill(row + dr[d], column + dc[d], 1, 0, size, grid);
  22. }
  23. return answer;
  24. }
  25. public static void main (String[] args) throws java.lang.Exception
  26. {
  27. Scanner kb = new Scanner(System.in);
  28. while (kb.hasNextInt()) {
  29. int size = kb.nextInt();
  30. int[][] graph = new int[size][size];
  31. for (int i = 0; i < size; i++) {
  32. String temp = kb.next();
  33. for (int j = 0; j < size; j++) {
  34. graph[i][j] = Character.getNumericValue(temp.charAt(j));
  35. }
  36. }
  37. System.out.println(floodFill(0,3,1,0,size,graph));
  38. }
  39. }
  40. }
Success #stdin #stdout 0.15s 321280KB
stdin
6
100100
001010 
000000
110000
111000
010100
8
01100101
01000001 
00011000 
00000010
11000011
10100010
10000001
01100000
stdout
3
0