Advertisement
Alekss33

Untitled

May 16th, 2019
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. package com.advanced;
  2.  
  3. import java.io.ByteArrayInputStream;
  4. import java.util.Arrays;
  5. import java.util.Scanner;
  6.  
  7. public class LargestArea {
  8. static int rowsIn;
  9. static int colsIn;
  10. static int checkedPosition;
  11.  
  12. public static void main(String[] args) {
  13.  
  14. Scanner input = new Scanner(System.in);
  15. int[] defineMatrix = Arrays.stream(input.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
  16. rowsIn = defineMatrix[0];
  17. colsIn = defineMatrix[1];
  18.  
  19.  
  20. int[][] matrix = new int[rowsIn][colsIn];
  21. for (int row = 0; row < rowsIn; row++) {
  22. for (int col = 0; col < colsIn; col++) {
  23. matrix[row][col] = Integer.parseInt(input.next());
  24. }
  25. }
  26.  
  27. int longestPath = 0;
  28. int currentValue;
  29. checkedPosition = 1111;
  30.  
  31. for (int rows = 0; rows < rowsIn; rows++) {
  32. for (int cols = 0; cols < colsIn; cols++) {
  33. if (matrix[rows][cols] != checkedPosition) {
  34. currentValue = matrix[rows][cols];
  35.  
  36. int size = getPathSize(matrix, rows, cols, currentValue);
  37. longestPath = Math.max(size, longestPath);
  38. matrix[rows][cols] = checkedPosition;
  39. }
  40. }
  41. }
  42. System.out.println(longestPath);
  43. }
  44.  
  45. private static int getPathSize(int[][] matrix, int rows, int cols, int currentValue) {
  46. if (!isInRange(matrix, rows, cols)) {
  47. return 0;
  48. }
  49. if (matrix[rows][cols] != currentValue) {
  50. return 0;
  51. }
  52.  
  53. matrix[rows][cols] = checkedPosition;
  54. int counter = 1;
  55.  
  56. for (int r = rows - 1; r <= rows + 1; r++) {
  57. for (int c = cols - 1; c <= cols + 1; c++) {
  58. if (r != rows || c != cols)
  59. counter += getPathSize(matrix, r, c, currentValue);
  60. }
  61. }
  62. return counter;
  63. }
  64.  
  65. private static boolean isInRange(int[][] matrix, int rows, int cols) {
  66. return rows >= 0 && rows < rowsIn && cols >= 0 && cols < colsIn;
  67. }
  68.  
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement