Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- namespace Algorithms
- {
- class Program
- {
- static char wall = '*';
- static char visited = 'v';
- static List<Area> areas = new List<Area>();
- static void Main(string[] args)
- {
- int rows = int.Parse(Console.ReadLine());
- int cols = int.Parse(Console.ReadLine());
- char[,] matrix = ReadMatrix(rows, cols);
- for (int row = 0; row < matrix.GetLength(0); row++)
- {
- for (int col = 0; col < matrix.GetLength(1); col++)
- {
- FindConnectedArea(matrix, row, col);
- }
- }
- Console.WriteLine($"Total areas found: {areas.Count}");
- int positionCount = 1;
- foreach (var area in areas.OrderByDescending(a => a.size))
- {
- Console.WriteLine($"Area #{positionCount++} at ({area.row}, {area.col}), size: {area.size}");
- }
- }
- private static void FindConnectedArea(char[,] matrix, int row, int col)
- {
- if (matrix[row, col] == wall || matrix[row, col] == visited)
- {
- return;
- }
- Area area = new Area(row, col);
- FillArea(matrix, row, col, area);
- areas.Add(area);
- }
- private static void FillArea(char[,] matrix, int row, int col, Area area)
- {
- if (!IsInRange(matrix, row, col)
- || matrix[row, col] == visited
- || matrix[row, col] == wall)
- {
- return;
- }
- matrix[row, col] = visited;
- area.size++;
- FillArea(matrix, row + 1, col, area);
- FillArea(matrix, row, col + 1, area);
- FillArea(matrix, row - 1, col, area);
- FillArea(matrix, row, col - 1, area);
- }
- private static bool IsInRange(char[,] matrix, int row, int col)
- {
- return row >= 0 && row < matrix.GetLength(0) && col >= 0 && col < matrix.GetLength(1);
- }
- private static char[,] ReadMatrix(int rows, int cols)
- {
- var matrix = new char[rows, cols];
- for (int i = 0; i < rows; i++)
- {
- var currentRow = Console.ReadLine().ToCharArray();
- for (int j = 0; j < currentRow.Length; j++)
- {
- matrix[i, j] = currentRow[j];
- }
- }
- return matrix;
- }
- class Area : IComparable<Area>
- {
- public int row;
- public int col;
- public int size;
- public Area(int row, int col)
- {
- this.row = row;
- this.col = col;
- this.size = 0;
- }
- public int CompareTo(Area other)
- {
- int comperator = other.size.CompareTo(this.size);
- if (comperator == 0)
- {
- comperator = this.row.CompareTo(other.row);
- }
- if (comperator == 0)
- {
- comperator = this.col.CompareTo(other.col);
- }
- return comperator;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment