Advertisement
BorislavBorisov

Търсене DFS Path in char matrix

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