Advertisement
Guest User

Untitled

a guest
Nov 14th, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class SmallWorld {
  4. public static void main(String[] args) {
  5. Scanner scanner = new Scanner(System.in);
  6. String[] gridSize = scanner.nextLine().split(" ");
  7. String[][] grid = new String[Integer.parseInt(gridSize[0])][Integer.parseInt(gridSize[1])];
  8. ArrayList<Integer> myArr = new ArrayList<>();
  9. int counter = 1;
  10. boolean[][] gridCheck = new boolean[Integer.parseInt(gridSize[0])][Integer.parseInt(gridSize[1])];
  11. for (int i = 0; i < Integer.parseInt(gridSize[0]); i++) {
  12. String inputString = scanner.nextLine();
  13. grid[i] = inputString.split("");
  14. }
  15. moveAroundGrid(grid, gridCheck, counter, myArr);
  16. Collections.sort(myArr, Collections.reverseOrder());
  17. myArr
  18. .forEach(System.out::println);
  19. }
  20.  
  21. public static void moveAroundGrid(String[][] grid, boolean[][] gridCheck, int counter, ArrayList<Integer> myArr){
  22. String test;
  23. int maxNumber = 0;
  24. if (grid.length == 0) {
  25. return;
  26. }
  27. for (int i = 0; i < grid.length; i++) {
  28. for (int j = 0; j < grid[0].length; j++) {
  29. if (gridCheck[i][j] || grid[i][j].equals("0")) {
  30. continue;
  31. }
  32. test = grid[i][j];
  33. counter = countOccurrencies(grid, gridCheck, i, j, test);
  34. myArr.add(counter);
  35. }
  36. }
  37. }
  38.  
  39. public static int countOccurrencies(String[][] grid, boolean[][] gridCheck, int row, int col, String test) {
  40. if (outOfGrid(grid, row, col)) {
  41. return 0;
  42. }
  43. if (gridCheck[row][col]) {
  44. return 0;
  45. }
  46. if (!grid[row][col].equals(test)) {
  47. return 0;
  48. }
  49. gridCheck[row][col] = true;
  50. return 1 + countOccurrencies(grid, gridCheck, row + 1, col, test)
  51. + countOccurrencies(grid, gridCheck, row, col + 1, test)
  52. + countOccurrencies(grid, gridCheck, row - 1, col, test)
  53. + countOccurrencies(grid, gridCheck, row, col - 1, test);
  54. }
  55.  
  56. private static boolean outOfGrid(String[][] grid, int row, int col) {
  57. return row < 0 || col < 0 || row >= grid.length || col >= grid[0].length;
  58. }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement