Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*07. * Write a program that finds the largest area of equal neighbor elements
- in a rectangular matrix and prints its size. Hint: you can use the algorithm
- "Depth-first search" or "Breadth-first search" (find them in Wikipedia).*/
- using System;
- class FindsLargestAreaOfEqualElements
- {
- static void Main()
- {
- string[,] field = {{"c", "b", "d", "j", "a", "a"},
- {"b", "a", "j", "c", "z", "a"},
- {"l", "a", "a", "j", "a", "a"},
- {"j", "a", "j", "a", "a", "l"},
- {"b", "a", "a", "a", "z", "a"}};
- int tempLength = 0;
- bool[,] temp = new bool[field.GetLength(0), field.GetLength(1)];
- int maxLength = 1;
- bool[,] largestArea = new bool[field.GetLength(0), field.GetLength(1)];
- for (int row = 0; row < field.GetLength(0); row++)
- {
- for ( int col = 0; col < field.GetLength(1); col++)
- {
- DepthFirstSearch(field, row, col, ref temp, ref tempLength);
- if (tempLength > maxLength)
- {
- maxLength = tempLength;
- for (int i = 0; i < temp.GetLength(0); i++)
- {
- for (int j = 0; j < temp.GetLength(1); j++)
- {
- largestArea[i, j] = temp[i, j];
- }
- }
- }
- tempLength = 0;
- temp = new bool[field.GetLength(0), field.GetLength(1)];
- }
- }
- for (int row = 0; row < field.GetLength(0); row++)
- {
- for (int col = 0; col < field.GetLength(1); col++)
- {
- if (largestArea[row, col])
- {
- Console.ForegroundColor = ConsoleColor.Green;
- Console.Write(field[row, col] + " ");
- Console.ForegroundColor = ConsoleColor.Gray;
- }
- else
- {
- Console.Write(field[row, col] + " ");
- }
- }
- Console.WriteLine();
- }
- }
- static void DepthFirstSearch(string[,] array, int row, int col, ref bool[,] temp, ref int tempLength)
- {
- temp[row, col] = true;
- tempLength += 1;
- for ( int r = row - 1; r <= row + 1; r++)
- {
- for (int c = col - 1; c <= col + 1; c++)
- {
- if (c < 0)
- {
- c++;
- }
- if (c > array.GetLength(1) - 1)
- {
- continue;
- }
- if (r < 0)
- {
- r++;
- }
- if (r > array.GetLength(0) - 1)
- {
- continue;
- }
- if (array[row, col] == array[r, c] && !temp[r, c])
- {
- temp[r, c] = true;
- DepthFirstSearch(array, r ,c, ref temp, ref tempLength);
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement