Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Linq;
- class LineInverter
- {
- static void Main()
- {
- int n = int.Parse(Console.ReadLine());
- char[][] matrix = new char[n][];
- for (int i = 0; i < n; i++)
- {
- matrix[i] = Console.ReadLine().ToCharArray();
- }
- int minSteps = 0;
- while (true)
- {
- if (IsBlack(matrix) || minSteps > n * n)
- {
- break;
- }
- var bestRow = FindBestRow(matrix);
- var bestCol = FindBestCol(matrix);
- if (bestRow.Item2 >= bestCol.Item2)
- {
- InvertRow(bestRow.Item1, matrix);
- }
- else
- {
- InvertCol(bestCol.Item1, matrix);
- }
- minSteps++;
- }
- Console.WriteLine(minSteps > n * n ? -1 : minSteps);
- }
- private static bool IsBlack(char[][] matrix)
- {
- int blackCount = matrix.Sum(m => matrix.Where((t, col) => m[col] == 'B').Count());
- return blackCount == matrix.Length*matrix.Length;
- }
- private static Tuple<int, int> FindBestCol(char[][] matrix)
- {
- int bestCol = 0;
- int bestCount = 0;
- for (int col = 0; col < matrix.Length; col++)
- {
- int count = matrix.Count(t => t[col] == 'W');
- if (count > bestCount)
- {
- bestCount = count;
- bestCol = col;
- }
- }
- return new Tuple<int, int>(bestCol, bestCount);
- }
- private static Tuple<int, int> FindBestRow(char[][] matrix)
- {
- int bestRow = 0;
- int bestCount = 0;
- for (int row = 0; row < matrix.Length; row++)
- {
- if (matrix[row].ToList().Count(c => c == 'W') > bestCount)
- {
- bestCount = matrix[row].ToList().Count(c => c == 'W');
- bestRow = row;
- }
- }
- return new Tuple<int, int>(bestRow, bestCount);
- }
- private static void InvertRow(int row, char[][] matrix)
- {
- for (int col = 0; col < matrix.Length; col++)
- {
- matrix[row][col] = matrix[row][col] == 'W' ? 'B' : 'W';
- }
- }
- private static void InvertCol(int col, char[][] matrix)
- {
- for (int row = 0; row < matrix.Length; row++)
- {
- matrix[row][col] = matrix[row][col] == 'W' ? 'B' : 'W';
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement