Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Largest Surface
- Description
- Write a program that finds the largest possible sequence of equal neighboring elements in a rectangular matrix and prints its size.
- Input
- On the first line you will receive the numbers N and M separated by a single space;
- On the next N lines there will be M numbers separated with spaces - the elements of the matrix;
- Output
- Print the size of the largest area of equal neighboring elements
- Constraints
- 3 <= N, M <= 1024
- Sample tests
- Input
- 5 6
- 1 3 2 2 2 4
- 3 3 3 2 4 4
- 4 3 1 2 3 3
- 4 3 1 3 3 1
- 4 3 3 3 1 1
- Output
- 13
- Hint: you can use the algorithm Depth-first search or Breadth-first search.
- package Recursion;
- import java.util.Scanner;
- public class LargestSurface {
- static int rows, cols;
- static int[][] matrix;
- static boolean[][] isVisited;
- static int maxSequence = 0;
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- String inputLine = scanner.nextLine();
- String[] inputStringArr = inputLine.split(" ");
- rows = Integer.parseInt(inputStringArr[0]);
- cols = Integer.parseInt(inputStringArr[1]);
- matrix = new int[rows][cols];
- isVisited = new boolean[rows][cols];
- for (int i = 0; i < rows; i++) {
- for (int j = 0; j < cols; j++) {
- matrix[i][j] = scanner.nextInt();
- }
- }
- System.out.println(getMaxSequence());
- }
- public static int calculateSurface(int[][] matrix, int row, int col, int currentNumber) {
- if (isValid(row, col)) {
- return 0;
- }
- if (isVisited(row, col, currentNumber)) {
- return 0;
- }
- int countNumbers = 1;
- isVisited[row][col] = true;
- countNumbers += calculateSurface(matrix, row - 1, col, currentNumber);
- countNumbers += calculateSurface(matrix, row + 1, col, currentNumber);
- countNumbers += calculateSurface(matrix, row, col - 1, currentNumber);
- countNumbers += calculateSurface(matrix, row, col + 1, currentNumber);
- return countNumbers;
- }
- public static boolean isValid(int row, int col) {
- return row < 0 || row >= rows || col < 0 || col >= cols;
- }
- public static boolean isVisited(int row, int col, int currentNumber) {
- return isVisited[row][col] || matrix[row][col] != currentNumber;
- }
- public static int getMaxSequence() {
- maxSequence = 0;
- for (int i = 0; i < rows; i++) {
- for (int j = 0; j < cols; j++) {
- if (!isVisited[i][j]) {
- int surface = calculateSurface(matrix, i, j, matrix[i][j]);
- maxSequence = Math.max(surface, maxSequence);
- }
- }
- }
- return maxSequence;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment