Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class SmallWorld {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- String[] gridSize = scanner.nextLine().split(" ");
- String[][] grid = new String[Integer.parseInt(gridSize[0])][Integer.parseInt(gridSize[1])];
- ArrayList<Integer> myArr = new ArrayList<>();
- int counter = 1;
- boolean[][] gridCheck = new boolean[Integer.parseInt(gridSize[0])][Integer.parseInt(gridSize[1])];
- for (int i = 0; i < Integer.parseInt(gridSize[0]); i++) {
- String inputString = scanner.nextLine();
- grid[i] = inputString.split("");
- }
- moveAroundGrid(grid, gridCheck, counter, myArr);
- Collections.sort(myArr, Collections.reverseOrder());
- myArr
- .forEach(System.out::println);
- }
- public static void moveAroundGrid(String[][] grid, boolean[][] gridCheck, int counter, ArrayList<Integer> myArr){
- String test;
- int maxNumber = 0;
- if (grid.length == 0) {
- return;
- }
- for (int i = 0; i < grid.length; i++) {
- for (int j = 0; j < grid[0].length; j++) {
- if (gridCheck[i][j] || grid[i][j].equals("0")) {
- continue;
- }
- test = grid[i][j];
- counter = countOccurrencies(grid, gridCheck, i, j, test);
- myArr.add(counter);
- }
- }
- }
- public static int countOccurrencies(String[][] grid, boolean[][] gridCheck, int row, int col, String test) {
- if (outOfGrid(grid, row, col)) {
- return 0;
- }
- if (gridCheck[row][col]) {
- return 0;
- }
- if (!grid[row][col].equals(test)) {
- return 0;
- }
- gridCheck[row][col] = true;
- return 1 + countOccurrencies(grid, gridCheck, row + 1, col, test)
- + countOccurrencies(grid, gridCheck, row, col + 1, test)
- + countOccurrencies(grid, gridCheck, row - 1, col, test)
- + countOccurrencies(grid, gridCheck, row, col - 1, test);
- }
- private static boolean outOfGrid(String[][] grid, int row, int col) {
- return row < 0 || col < 0 || row >= grid.length || col >= grid[0].length;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement