Advertisement
stanevplamen

DFS matrix

Sep 21st, 2022
1,005
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.49 KB | Software | 0 0
  1. using System;
  2.  
  3. public class DFSExample
  4. {
  5.     static char[,] matrix = new char[7, 7]
  6.     {
  7.         {' ',' ',' ','X','X','X',' '},
  8.         {' ','X',' ',' ',' ','X',' '},
  9.         {' ','X',' ','X','X','X',' '},
  10.         {' ','X',' ',' ',' ',' ',' '},
  11.         {' ','X',' ','X','X','X',' '},
  12.         {' ','X','X','X','X','X',' '},
  13.         {'E',' ',' ',' ',' ',' ',' '},
  14.     };
  15.  
  16.     static void PrintMatrix()
  17.     {
  18.         for (int i = 0; i < matrix.GetLength(0); i++)
  19.         {
  20.             for (int j = 0; j < matrix.GetLength(1); j++)
  21.             {
  22.                 if (matrix[i, j] == '*')
  23.                 {
  24.                     //Console.ForegroundColor = System.ConsoleColor.Red;
  25.                 }
  26.                 else
  27.                 {
  28.                     //Console.ForegroundColor = System.ConsoleColor.White;
  29.                 }
  30.                 Console.Write(matrix[i, j] + " ");
  31.             }
  32.             Console.WriteLine();
  33.         }
  34.         Console.WriteLine();
  35.         Console.WriteLine();
  36.     }
  37.     static bool InRange(int row, int col)
  38.     {
  39.         bool rowInRange = row >= 0 && row < matrix.GetLength(0);
  40.         bool colInRange = col >= 0 && col < matrix.GetLength(1);
  41.         return rowInRange && colInRange;
  42.     }
  43.  
  44.     static void FindPathToExit(int row, int col)
  45.     {
  46.         if (!InRange(row, col))
  47.         {
  48.             return;
  49.         }
  50.  
  51.         if (matrix[row, col] == 'E')
  52.         {
  53.             PrintMatrix();
  54.         }
  55.  
  56.         if (matrix[row, col] != ' ')
  57.         {
  58.             return;
  59.         }
  60.  
  61.         matrix[row, col] = '*';
  62.         FindPathToExit(row, col - 1); // left
  63.         FindPathToExit(row - 1, col); // up
  64.         FindPathToExit(row, col + 1); // right
  65.         FindPathToExit(row + 1, col); // down
  66.         matrix[row, col] = ' ';
  67.     }
  68.  
  69.     public static void Main(string[] args)
  70.     {
  71.         FindPathToExit(0, 6);
  72.     }
  73. }
  74.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement