Advertisement
Guest User

Untitled

a guest
Nov 13th, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. package com.telerikacademy;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.List;
  6. import java.util.Scanner;
  7.  
  8. public class MatrixTask {
  9. static int count;
  10. static List<Integer> results = new ArrayList<>();
  11.  
  12. public static boolean inBounds(int [][] grid, int row, int column){
  13. return (row >= 0 && column >= 0 && row < grid.length && column < grid[0].length);
  14. }
  15.  
  16. public static void getCount(int [][]grid, int row, int column){
  17.  
  18. if (!inBounds(grid, row, column)) {
  19. return;
  20. }
  21. if(grid[row][column]== 0) {
  22. return;
  23. }
  24.  
  25. if (grid[row][column]==1) {
  26. count++;
  27. grid[row][column] = 0;
  28. }
  29. getCount(grid, row+1, column);
  30. getCount(grid, row-1, column);
  31. getCount(grid, row, column+1);
  32. getCount(grid, row, column-1);
  33. }
  34.  
  35. public static void getElements(int [][] grid){
  36.  
  37. for (int i = 0; i <grid.length ; i++) {
  38. for (int j = 0; j <grid[0].length; j++) {
  39. count = 0;
  40.  
  41. if(grid[i][j] == 0) {
  42. continue;
  43. } else {
  44. getCount(grid, i, j);
  45. if (count!= 0) {
  46. results.add(count);
  47. }
  48. }
  49. }
  50.  
  51. }
  52. }
  53.  
  54. public static void main(String[] args) {
  55. Scanner scanner = new Scanner(System.in);
  56. int rows = Integer.parseInt(scanner.nextLine());
  57. int columns = Integer.parseInt(scanner.nextLine());
  58. int [][] grid = new int [rows][columns];
  59.  
  60. for (int i = 0; i <rows; i++) {
  61. String input = scanner.nextLine();
  62. String [] arr = input.split("");
  63. for (int j = 0; j <columns; j++) {
  64. grid[i][j] = Integer.parseInt(arr[j]);
  65. }
  66. }
  67.  
  68. getElements(grid);
  69. Collections.sort(results, Collections.reverseOrder());
  70. if (!results.isEmpty()) {
  71. for (int i = 0; i < results.size(); i++) {
  72. System.out.printf("%s\n", results.get(i));
  73. }
  74. } else {
  75. System.out.println("0");
  76. }
  77. }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement