使用c#
思路:从起点出发,走0代表可达路径,并用数字2标记已走路径,死胡同就弹栈,直到终点
using System;
using System.Collections.Generic;
using System.Text;
using static System.Console;
namespace DataStructure
{
public class Node//路径节点
{
public int x, y;
public Node next;
public Node (int x,int y)
{
this.x = x;
this.y = y;
this.next = null;
}
}
public class TraceRecord//路径结构,使用栈
{
public Node first;
public Node last;
public bool IsEmpty()
{
return first == null;
}
public void insertNode(int x,int y)//入栈
{
Node node = new Node(x, y);
if (this.IsEmpty())
{
first = node;
last = node;
}
else
{
last.next = node;
last = node;
}
}
public void deleteNode()//出栈
{
if (this.IsEmpty())
{
WriteLine("队列已经空了");
return;
}
Node tmp = first;
while(tmp.next != last)
{
tmp = tmp.next;
}
tmp.next = last.next;
last = tmp;
}
}
class MazePathFinding
{
public static int ExitX = 8,ExitY = 10;
public static int[,] MAZE = {//迷宫初始化
{1,1,1,1,1,1,1,1,1,1,1,1}, //声明迷宫数组
{1,0,0,0,1,1,1,1,1,1,1,1},
{1,1,1,0,1,1,0,0,0,0,1,1},
{1,1,1,0,1,1,0,1,1,0,1,1},
{1,1,1,0,0,0,0,1,1,0,1,1},
{1,1,1,0,1,1,0,1,1,0,1,1},
{1,1,1,0,1,1,0,1,1,0,1,1},
{1,1,1,1,1,1,0,1,1,0,1,1},
{1,1,0,0,0,0,0,0,1,0,0,1},
{1,1,1,1,1,1,1,1,1,1,1,1}
};
public static int checkExit(int x,int y,int exitX,int exitY)
{
if(x == exitX && y == exitY)//判断出口合法性,是否抵达终点
{
if(MAZE[x-1,y]==1 || MAZE[x,y-1] == 1 || MAZE[x , y+1] == 1 || MAZE[x + 1, y] == 2)
{
return 1;
}
if (MAZE[x - 1, y] == 1 || MAZE[x, y - 1] == 1 || MAZE[x, y + 1] == 2 || MAZE[x + 1, y] == 1){
return 1;
}
if(MAZE[x - 1, y] == 1 || MAZE[x, y - 1] == 2 || MAZE[x, y + 1] == 1 || MAZE[x + 1, y] == 1)
{
return 1;
}
if (MAZE[x - 1, y] == 2 || MAZE[x, y - 1] == 1 || MAZE[x, y + 1] == 1 || MAZE[x + 1, y] == 1)
{
return 1;
}
}
return 0;//不是终点
}
public static void startMazeMain()//启动函数
{
int i, j, x, y;
TraceRecord path = new TraceRecord();//路径节点存储栈
x = 1; y = 1;
WriteLine("迷宫的路径(0标记的部分)");
for (i = 0; i < 10; i++)//打印迷宫
{
for (j = 0; j < 12; j++)
{
Write(MAZE[i, j]);
}
Write("\n");
}
while (x<=ExitX && y<=ExitY)//不满足终点的条件就一直循环
{
MAZE[x, y] = 2;
if(MAZE[x-1,y] == 0)
{
x -= 1;
path.insertNode(x, y);
}
else if (MAZE[x + 1, y] == 0)
{
x += 1;
path.insertNode(x, y);
}
else if (MAZE[x, y - 1] == 0)
{
y -= 1;
path.insertNode(x, y);
}
else if (MAZE[x, y + 1] == 0)
{
y += 1;
path.insertNode(x, y);
}
else if(checkExit(x,y,ExitX,ExitY)==1)
{
break;
}
else//死胡同就弹栈
{
MAZE[x, y] = 2;
path.deleteNode();
x = path.last.x;
y = path.last.y;
}
}
WriteLine("\n[老鼠走过的路径(2标记的部分)]");
for (i = 0; i < 10; i++)//打印路径图
{
for (j = 0; j < 12; j++)
{
Write(MAZE[i, j]);
}
WriteLine();
}
ReadKey();
}
}
}