Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- //We are given a matrix of strings of size N x M. Sequences in the matrix we define as sets of several neighbour elements located on the same line, column or diagonal. Write a program that finds the longest sequence of equal strings in the matrix. Examples:
- class FindTheLongestSequence
- {
- static void Main()
- {
- List<string> resultList = new List<string>();
- List<string> currentList = new List<string>();
- var matrix = new string[,] {{"ha","fifi","ho","hi"}, {"fo","ha","hi","xx"},{"xxx", "ho", "ha","xx"}};
- for (int row = 0; row < matrix.GetLength(0); row++)
- {
- int index = 0;
- for (int col = 0; col < matrix.GetLength(1); col++)
- {
- //here matrix[row, col] is our starting position;
- for (int i = 0; i < matrix.GetLength(1) - col; i++) //check horizontally
- {
- if (matrix[row, col + i] != matrix[row, col])
- {
- break;
- }
- currentList.Add(matrix[row, col]);
- }
- if (currentList.Count > resultList.Count)
- {
- resultList = currentList.ToList(); //this keeps our current identical sequence.
- }
- currentList.Clear();
- for (int i = 0; i < matrix.GetLength(0) - row; i++) // check vertically
- {
- if (matrix[row + i, col] != matrix[row, col])
- {
- break;
- }
- currentList.Add(matrix[row, col]);
- }
- if (currentList.Count > resultList.Count)
- {
- resultList = currentList.ToList();
- }
- currentList.Clear();
- while (row + index < matrix.GetLength(0) && col + index < matrix.GetLength(1) && matrix[row + index, col + index] == matrix[row,col]) //check left-right diagonal
- {
- currentList.Add(matrix[row, col]);
- index++;
- }
- if (currentList.Count > resultList.Count)
- {
- resultList = currentList.ToList();
- }
- currentList.Clear();
- index = 0;
- while (row + index < matrix.GetLength(0) && col - index >= 0 && matrix[row + index, col - index] == matrix[row,col]) //check right-left giagonal
- {
- currentList.Add(matrix[row, col]);
- index++;
- }
- if (currentList.Count > resultList.Count)
- {
- resultList = currentList.ToList();
- }
- currentList.Clear();
- index = 0;
- }
- }
- Console.WriteLine(string.Join(" ", resultList));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment