Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //* Write a program that finds the largest area of equal neighbor elements in a rectangular matrix and prints its size. Example:
- // 1 3 2 2 2 4
- // 3 3 3 2 4 4
- // 4 3 1 2 3 3 --> 13
- // 4 3 1 3 3 1
- // 4 3 3 3 1 1
- // Hint: you can use the algorithm "Depth-first search" or "Breadth-first search" (find them in Wikipedia).
- using System;
- class LargestArea
- {
- static bool[,] isVisited;
- static int count;
- static void Main()
- {
- //Input
- int[,] testMatrix = {
- { 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 }
- };
- //Declare a bool matrix, where if the position is checked the cell becomes true
- isVisited = new bool[testMatrix.GetLength(0), testMatrix.GetLength(1)];
- for (int row = 0; row < isVisited.GetLength(0); row++)
- {
- for (int col = 0; col < isVisited.GetLength(1); col++)
- {
- isVisited[row, col] = false;
- }
- }
- //Call SearchEquals method for each element of the matrix
- int bestCount = 1;
- int mostFrequent = testMatrix[0, 0];
- for (int row = 0; row < testMatrix.GetLength(0); row++)
- {
- for (int col = 0; col < testMatrix.GetLength(1); col++)
- {
- count = 0;
- SearchEquals(testMatrix, row, col);
- if (count > bestCount)
- {
- bestCount = count;
- mostFrequent = testMatrix[row, col];
- }
- }
- }
- //Print the result
- Console.WriteLine("{0} --> {1} times ", mostFrequent, bestCount);
- }
- //Check is cell in the array
- static bool IsCellInMatrix(int[,] matrix, int i, int j)
- {
- return i >= 0 && i < matrix.GetLength(0) && j >= 0 && j < matrix.GetLength(1);
- }
- //Searching equals elements in position(row, col)
- static void SearchEquals(int[,] matrix, int row, int col)
- {
- int value = matrix[row, col];
- isVisited[row, col] = true;
- count++;
- if (IsCellInMatrix(matrix, row, col + 1) && matrix[row, col + 1] == value && isVisited[row, col + 1] == false)
- {
- SearchEquals(matrix, row, col + 1);
- }
- if (IsCellInMatrix(matrix, row, col - 1) && matrix[row, col - 1] == value && isVisited[row, col - 1] == false)
- {
- SearchEquals(matrix, row, col - 1);
- }
- if (IsCellInMatrix(matrix, row - 1, col) && matrix[row - 1, col] == value && isVisited[row - 1, col] == false)
- {
- SearchEquals(matrix, row - 1, col);
- }
- if (IsCellInMatrix(matrix, row + 1, col) && matrix[row + 1, col] == value && isVisited[row + 1, col] == false)
- {
- SearchEquals(matrix, row +1 , col);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement