var points =new char[5,6]{
{'1','0','1','1','1','0'},
{'1','1','1','0','1','0'},
{'1','0','0','1','1','0'},
{'1','0','0','1','0','0'},
{'1','0','0','1','1','0'} };
PrintMaze(points);
MazePuzzle(points, 0, 0, 4, 4);
void MazePuzzle(char[,] maze, int row, int col, int outrow, int outcol)
{
maze[row,col] = 'Y'; // 将各个走过的区域标记为 Y
//如果行走至终点,表明有从起点到终点的路线
if (row == outrow && col == outcol)
{
Console.WriteLine("成功走出迷宫,路线图为:");
PrintMaze(maze);
return;
}
//尝试向上移动
if (CanMove(maze, row - 1, col)) {
MazePuzzle(maze, row - 1, col, outrow, outcol);
//如果程序不结束,表明此路不通,恢复该区域的标记
maze[row - 1,col] = '1';
}
//尝试向左移动
if (CanMove(maze, row, col - 1)) {
MazePuzzle(maze, row, col - 1, outrow, outcol);
//如果程序不结束,表明此路不通,恢复该区域的标记
maze[row,col - 1] = '1';
}
//尝试向下移动
if (CanMove(maze, row + 1, col)) {
MazePuzzle(maze, row + 1, col, outrow, outcol);
//如果程序不结束,表明此路不通,恢复该区域的标记
maze[row + 1,col] = '1';
}
//尝试向右移动
if (CanMove(maze, row, col + 1)) {
MazePuzzle(maze, row, col + 1, outrow, outcol);
//如果程序不结束,表明此路不通,恢复该区域的标记
maze[row,col + 1] = '1';
}
}
//输出行走路线
void PrintMaze(char [,] maze) {
for (int rowIndex = 0; rowIndex < maze.GetLength(0); rowIndex++)
{
for (int cellIndex = 0; cellIndex < maze.GetLength(1); cellIndex++)
{
Console.Write($" {maze[rowIndex,cellIndex]} ");
}
Console.WriteLine();
}
}
//判断(row,col)区域是否可以移动
bool CanMove(char [,] maze, int row, int col) {
//如果目标区域位于地图内,不是黑色区域,且尚未移动过,返回 true:反之,返回 false
return row >= 0 && row <= maze.GetLength(0) - 1 && col >= 0 && col <= maze.GetLength(1) - 1 && maze[row,col] != '0' && maze[row,col] != 'Y';
}