
程序代码:
/**
* @文件名:App.cs
* @作 者:寒风中的细雨
* @时 间:2012/5/14/
* @概 述:使用栈实现 迷宫
*/
using System;
enum Dir
{
EAST,//东
WEST,//西
SOUTH,//南
NORTH,//北
END
}
class Pos//坐标
{
int m_Row;//行号
int m_Col;//列号
Dir m_Dir;//方向
public Pos(int nRow, int nCol, Dir nDir)
{
m_Row = nRow;
m_Col = nCol;
m_Dir = nDir;
}
public int Row
{
get { return m_Row; }
set { m_Row = value; }
}
public int Col
{
get { return m_Col; }
set { m_Col = value; }
}
public Dir Dir
{
get { return m_Dir; }
set { m_Dir = value; }
}
public bool Equal(Pos obj)
{
return m_Col == obj.m_Col && m_Row == obj.m_Row;
}
}
class App
{
static int[,] map =//迷宫地图
{ //0 1 2 3 4 5 6 7 8 9
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1},//0
{1, 0, 0, 1, 0, 0, 0, 1, 0, 1},//1
{1, 0, 0, 1, 0, 0, 0, 1, 0, 1},//2
{1, 0, 0, 0, 0, 1, 1, 0, 0, 1},//3
{1, 0, 1, 1, 1, 0, 0, 0, 0, 1},//4
{1, 0, 0, 0, 1, 0, 0, 0, 0, 1},//5
{1, 0, 1, 0, 0, 0, 1, 0, 0, 1},//6
{1, 0, 1, 1, 1, 0, 1, 1, 0, 1},//7
{1, 1, 0, 0, 0, 0, 0, 0, 0, 1},//8
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1},//9
};
static LinkStack<Pos> stack = new LinkStack<Pos>();
static void Main(string[] args)
{
Pos startPos = new Pos(1, 1, Dir.EAST);//起点
Pos endPos = new Pos(8, 8, Dir.EAST);//终点
stack.Push(startPos);//压入起点
map[startPos.Row, startPos.Col] = 1;
MazePath(endPos);//
Console.WriteLine("下面为行走轨迹...");
PrintTrace();
}
//走迷宫
static void MazePath(Pos endPos)
{
while (!stack.IsEmpty() && !stack.GetTop().Equal(endPos))
{
Pos tmpPos = stack.GetTop();
switch (tmpPos.Dir)
{
case Dir.EAST://东
tmpPos.Dir = Dir.SOUTH;//修改方向
if (0 == map[tmpPos.Row, tmpPos.Col + 1])
{
stack.Push(new Pos(tmpPos.Row, tmpPos.Col+1, Dir.EAST));
map[tmpPos.Row, tmpPos.Col + 1] = 1;
}
break;
case Dir.SOUTH://南
tmpPos.Dir = Dir.WEST;//修改方向
if (0 == map[tmpPos.Row+1, tmpPos.Col])
{
stack.Push(new Pos(tmpPos.Row + 1, tmpPos.Col, Dir.EAST));
map[tmpPos.Row + 1, tmpPos.Col] = 1;
}
break;
case Dir.WEST://西
tmpPos.Dir = Dir.NORTH;//修改方向
if (0 == map[tmpPos.Row, tmpPos.Col-1])
{
stack.Push(new Pos(tmpPos.Row, tmpPos.Col - 1, Dir.EAST));
map[tmpPos.Row, tmpPos.Col - 1] = 1;
}
break;
case Dir.NORTH://北
tmpPos.Dir = Dir.END;//修改方向
if (0 == map[tmpPos.Row-1, tmpPos.Col])
{
stack.Push(new Pos(tmpPos.Row-1, tmpPos.Col, Dir.EAST));
map[tmpPos.Row - 1, tmpPos.Col] = 1;
}
break;
case Dir.END://出栈
stack.Pop();
break;
default:
break;
}
}
}
//输出行走轨迹
static void PrintTrace()
{
if (!stack.IsEmpty())
{
Pos tmpPos = stack.GetTop();
stack.Pop();
PrintTrace();
Console.WriteLine("("+tmpPos.Row+", "+tmpPos.Col+")");
}
}
}