Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Scanner;
- public class SmallWorldTwo {
- public static ArrayList<Integer> list = new ArrayList<>();
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- String[] input = scanner.nextLine().split(" ");
- int cols = Integer.parseInt(input[0]);
- int rows = Integer.parseInt(input[1]);
- String[][] matrix = new String[cols][rows];
- for (int i = 0; i < cols; i++) {
- matrix[i] = scanner.nextLine().split("");
- }
- for (int row = 0; row < matrix.length; row++) {
- for (int col = 0; col < matrix[row].length; col++) {
- if (matrix[row][col].equals("1")) {
- list.add(dfs(matrix, row, col));
- }
- }
- }
- list.sort(Collections.reverseOrder());
- for (Integer integer : list) {
- System.out.println(integer);
- }
- }
- public static int dfs(String[][] matrix, int row, int col) {
- if (row < 0 || col < 0 || row >= matrix.length || col >= matrix[row].length) {
- return 0;
- }
- String position = matrix[row][col];
- if (!position.equals("1")) {
- return 0;
- }
- int count = 1;
- matrix[row][col] = "0";
- count += dfs(matrix, row - 1, col);
- count += dfs(matrix, row + 1, col);
- count += dfs(matrix, row, col - 1);
- count += dfs(matrix, row, col + 1);
- return count;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement