Venciity

[ Telerik C#] MultidimArrays 03-LongestSequenceInMatrix

Feb 28th, 2014
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.19 KB | None | 0 0
  1. using System;
  2.  
  3. class Program
  4. {
  5.     static void PrintMatrix(string[,] matrix)
  6.     {
  7.         int cellSize = matrix[0, 0].Length;
  8.         foreach (string cell in matrix) cellSize = Math.Max(cellSize, cell.Length);
  9.  
  10.         for (int i = 0; i < matrix.GetLength(0); i++)
  11.             for (int j = 0; j < matrix.GetLength(1); j++)
  12.                 Console.Write(matrix[i, j].PadRight(cellSize, ' ') + (j != matrix.GetLength(1) - 1 ? " " : "\n"));
  13.     }
  14.  
  15.     static bool IsTraversable(string[,] matrix, int row, int col)
  16.     {
  17.         return row >= 0 && row < matrix.GetLength(0) && col >= 0 && col < matrix.GetLength(1);
  18.     }
  19.  
  20.     static int maxSum = 0;
  21.     static string maxValue;
  22.  
  23.     static int[,] directions = { { 0, 1 }, { 1, 0 }, { 1, 1 }, { 1, -1 } };
  24.     static void DFS(string[,] matrix, bool[, ,] used, int row, int col)
  25.     {
  26.         // Go in all directions
  27.         for (int direction = 0; direction < directions.GetLength(0); direction++)
  28.         {
  29.             if (used[row, col, direction]) continue; // Already visited in this direction
  30.  
  31.             int currentSum = 0;
  32.             int _row = row, _col = col;
  33.  
  34.             while (IsTraversable(matrix, _row, _col) && matrix[row, col] == matrix[_row, _col])
  35.             {
  36.                 currentSum++;
  37.  
  38.                 used[_row, _col, direction] = true;
  39.  
  40.                 _row += directions[direction, 0];
  41.                 _col += directions[direction, 1];
  42.             }
  43.  
  44.             if (currentSum > maxSum)
  45.             {
  46.                 maxSum = currentSum;
  47.                 maxValue = matrix[row, col];
  48.             }
  49.         }
  50.     }
  51.  
  52.     static void Main()
  53.     {
  54.         string[,] matrix = { { "ha", "fifi", "ho", "hi" }, { "fo", "ha", "hi", "xx" }, { "xxx", "ho", "ha", "xx" } };
  55.         //string[,] matrix = { { "s", "qq", "s" }, { "pp", "pp", "s" }, { "pp", "qq", "s" } };
  56.  
  57.         bool[, ,] used = new bool[matrix.GetLength(0), matrix.GetLength(1), directions.GetLength(0)];
  58.  
  59.         for (int i = 0; i < matrix.GetLength(0); i++)
  60.             for (int j = 0; j < matrix.GetLength(1); j++)
  61.                 DFS(matrix, used, i, j);
  62.  
  63.         PrintMatrix(matrix);
  64.         Console.WriteLine(maxValue + " " + maxSum);
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment