Venciity

[ Telerik C#] MultidimArrays 07-MaxAdjacentVertices

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