Advertisement
SvetoslavUzunov

Path to Labyrinth

Apr 19th, 2021
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.55 KB | None | 0 0
  1. using System;
  2.  
  3. namespace Recursion
  4. {
  5.     class Program
  6.     {
  7.         static char[,] labyrinth =
  8.         {
  9.             {' ', ' ', ' '},
  10.             {'*', '*', ' '},
  11.             {' ', ' ', ' '},
  12.             {' ', ' ', 'e'}
  13.         };
  14.  
  15.         static void Main()
  16.         {
  17.             FindPath(0, 0, 's');
  18.         }
  19.  
  20.         static char[] path = new char[labyrinth.GetLength(0) * labyrinth.GetLength(1)];
  21.         static int position = 0;
  22.         static void FindPath(int row, int col, char direction)
  23.         {
  24.             if (row < 0 || col < 0 || row >= labyrinth.GetLength(0) || col >= labyrinth.GetLength(1))
  25.             {
  26.                 return;
  27.             }
  28.  
  29.             path[position] = direction;
  30.             position++;
  31.             if (labyrinth[row, col] == 'e')
  32.             {
  33.                 PrintDirections(path, 1, position - 1);
  34.             }
  35.  
  36.             if (labyrinth[row, col] == ' ')
  37.             {
  38.                 labyrinth[row, col] = 's';
  39.  
  40.                 FindPath(row, col - 1, 'L');
  41.                 FindPath(row - 1, col, 'U');
  42.                 FindPath(row, col + 1, 'R');
  43.                 FindPath(row + 1, col, 'D');
  44.  
  45.                 labyrinth[row, col] = ' ';
  46.             }
  47.             position--;
  48.         }
  49.  
  50.         static void PrintDirections(char[] path, int start, int end)
  51.         {
  52.             Console.Write("Find path to the exit: ");
  53.             for (var i = start; i <= end; i++)
  54.             {
  55.                 Console.Write(path[i]);
  56.             }
  57.             Console.WriteLine();
  58.         }
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement