Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.telerikacademy;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.List;
- import java.util.Scanner;
- public class MatrixTask {
- static int count;
- static List<Integer> results = new ArrayList<>();
- public static boolean inBounds(int [][] grid, int row, int column){
- return (row >= 0 && column >= 0 && row < grid.length && column < grid[0].length);
- }
- public static void getCount(int [][]grid, int row, int column){
- if (!inBounds(grid, row, column)) {
- return;
- }
- if(grid[row][column]== 0) {
- return;
- }
- if (grid[row][column]==1) {
- count++;
- grid[row][column] = 0;
- }
- getCount(grid, row+1, column);
- getCount(grid, row-1, column);
- getCount(grid, row, column+1);
- getCount(grid, row, column-1);
- }
- public static void getElements(int [][] grid){
- for (int i = 0; i <grid.length ; i++) {
- for (int j = 0; j <grid[0].length; j++) {
- count = 0;
- if(grid[i][j] == 0) {
- continue;
- } else {
- getCount(grid, i, j);
- if (count!= 0) {
- results.add(count);
- }
- }
- }
- }
- }
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- int rows = Integer.parseInt(scanner.nextLine());
- int columns = Integer.parseInt(scanner.nextLine());
- int [][] grid = new int [rows][columns];
- for (int i = 0; i <rows; i++) {
- String input = scanner.nextLine();
- String [] arr = input.split("");
- for (int j = 0; j <columns; j++) {
- grid[i][j] = Integer.parseInt(arr[j]);
- }
- }
- getElements(grid);
- Collections.sort(results, Collections.reverseOrder());
- if (!results.isEmpty()) {
- for (int i = 0; i < results.size(); i++) {
- System.out.printf("%s\n", results.get(i));
- }
- } else {
- System.out.println("0");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement