//c#迷宫问题,使用栈实现,不是最优解(只是搜索出一可行路径)
实现思路:1、迷宫用二维数组表示,入库为数组的第一个节点,出口为数组的最后一个节点,0代表可通行,1代表不可同行。
2、先把开始节点放入栈中(同时数据变为2),然后按照搜索方位去找下一个节点,如果下一节点可通过,则存入栈 中,同时把节点数据变为2(表示已搜索过)。如果下一节点不能通过,则变化搜索方向继续搜索,如果此节点的4 个方向都不能通过,则把当前节点从栈中删除,回到前一节点继续搜索。
3、如果栈空,则表示没有可通过路径,如果搜索到了最后一个节点,则表示找到可通行路径,输出栈内路径
using System;using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int[,] arr = new int[10, 10]{
{0,0,1,1,1,1,1,1,1,1},
{1,0,1,1,0,0,0,1,0,1},
{0,0,0,1,0,0,0,1,0,1},
{0,1,1,0,0,0,1,0,0,1},
{0,1,1,1,1,0,0,0,0,1},
{0,1,0,0,1,0,0,0,0,1},
{0,1,1,0,0,0,1,0,0,1},
{0,1,1,1,1,0,1,1,0,1},
{0,1,0,0,0,0,0,0,0,1},
{0,0,0,1,1,1,1,1,0,0}
};
Stack<Element> stack = new Stack<Element>();
Element start = new Element(0, 0, "E");
stack.Push(start);
arr[0, 0] = 2;
int count = 0;//搜索过的方位数
int len=arr.GetLength(0);
do
{
Element cur = stack.Peek();
if (cur.pox == len-1 && cur.poy == len-1)//如果当前节点是最后节点,结束搜索
{
break;
}
Element next = GetNextEle(cur);//当前节点的下一节点。
if (CanPass(next,arr))//下一节点可通过
{
stack.Push(next);//可通过的阶段保存到栈中
arr[next.pox, next.poy] = 2;//已搜索过的节点变为2.
count = 0;//重新计数
}
else if(count<4)
{
cur.dir = GetNextDir(cur.dir);//变化方向继续搜索。
count++;//搜索了一个方向,记录加1.
continue;
}
else
{
stack.Pop();//4个方向都不通,则从栈中移除当前节点(过来的节点已变成了2)
count = 0;//重新记录搜索次数
}
} while (stack.Count > 0);//栈空则表示没有通路;
if (stack.Count == 0)
{
Console.WriteLine("没有通路");
}
else
{
for (int i = stack.Count; i > 0; i--)
{
Element ele = stack.Pop();
Console.WriteLine(ele.pox + " " + ele.poy + " " + ele.dir);
}
}
Console.Read();
}
//搜索方向E->S->W->N(又下左上,因为最后的节点在又)
private static string GetNextDir(string dir)
{
switch (dir)
{
case "E":
dir = "S";
break;
case "S":
dir = "W";
break;
case "W":
dir = "N";
break;
case "N":
dir = "E";
break;
}
return dir;
}
private static Element GetNextEle(Element cur)
{
Element ele = null;
int x=cur.pox;
int y=cur.poy;
switch (cur.dir)
{
case "E":
ele = new Element(x, ++y, "E");
break;
case "S":
ele = new Element(++x, y, "E");
break;
case "W":
ele = new Element(x, --y, "E");
break;
case "N":
ele = new Element(--x, y, "E");
break;
}
return ele;
}
private static bool CanPass(Element ele,int[,] arr)
{
int len=arr.GetLength(0);
if (ele.pox >= 0 && ele.poy >= 0 && ele.pox < len && ele.poy < len)
{
if (arr[ele.pox, ele.poy] == 0)
return true;
return false;
}
else
return false;
}
}
}
public class Element
{
public Element(int x, int y, string order)
{
this.pox = x;
this.poy = y;
this.dir = order;
}
public int pox;
public int poy;
public string dir;
}