Venciity

[ Telerik C#] MultidimArrays 01-MatrixInitializationD

Feb 26th, 2014
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.67 KB | None | 0 0
  1. using System;
  2.  
  3. class Program
  4. {
  5.     static void PrintMatrix(int[,] matrix)
  6.     {
  7.         int cellSize = (int)Math.Log10(matrix.Length) + 1;
  8.         for (int i = 0; i < matrix.GetLength(0); i++)
  9.             for (int j = 0; j < matrix.GetLength(1); j++)
  10.                 Console.Write(Convert.ToString(matrix[i, j]).PadRight(cellSize, ' ') + (j != matrix.GetLength(1) - 1 ? " " : "\n"));
  11.     }
  12.  
  13.     static bool IsTraversable(int[,] matrix, int x, int y)
  14.     {
  15.         return x >= 0 && x < matrix.GetLength(0) && y >= 0 && y < matrix.GetLength(1) && matrix[x, y] == 0;
  16.     }
  17.  
  18.     static int direction = 0;
  19.     static int[,] directions = new int[,] { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } };
  20.     static void DFS(int[,] matrix, int row, int col, int current)
  21.     {
  22.         matrix[row, col] = current; // Set level
  23.  
  24.         if (current == matrix.Length) return; // End of recursion
  25.  
  26.         // Find the next cell, we should visit
  27.         int _row = row + directions[direction, 0];
  28.         int _col = col + directions[direction, 1];
  29.  
  30.         // Check if the next cell is traversable
  31.         // Reset the direction and find the first free one if it isn't
  32.         if (!IsTraversable(matrix, _row, _col)) direction = -1;
  33.         while (!IsTraversable(matrix, _row, _col))
  34.         {
  35.             direction++;
  36.             _row = row + directions[direction, 0];
  37.             _col = col + directions[direction, 1];
  38.         }
  39.  
  40.         DFS(matrix, _row, _col, current + 1); // Go to the next cell and increment level
  41.     }
  42.  
  43.     static void Main()
  44.     {
  45.         int n = 4;
  46.  
  47.         int[,] matrix = new int[n, n];
  48.         DFS(matrix, 0, 0, 1);
  49.  
  50.         PrintMatrix(matrix);
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment