#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <queue>
#include <stack>
using namespace std;
const int SIZE = 6;
//边界数组,四个方向,按照下、右、上、左的顺序
int coordinate[8][2] = {{-1,0}, {-1,1}, {0,1}, {1,1},{1,0},{1,-1},{0,-1},{-1,-1}};
stack<int> sx;
stack<int> sy;
stack<int> sxCopy;
stack<int> syCopy;
int mazeBfs[SIZE][SIZE]={
0,0,0,0,0,0,
0,0,0,0,0,0,
0,0,0,0,0,0,
0,0,1,0,0,0,
0,0,0,0,0,0,
0,0,0,0,0,0
};
//广搜用的迷宫
int mazeDfs[SIZE][SIZE]={
0,0,0,0,0,0,
0,0,0,0,0,0,
0,0,0,0,0,0,
0,0,1,0,0,0,
0,0,0,0,0,0,
0,0,0,0,0,0
}; //深搜用的迷宫
int m = 6;
int n = 6;
int p = 0;
int q = 0;
int r = 5;
int s = 5;
int ShortestPathLength; //最短路径的长度
int ShortestPahtNumber; //最短路径的条数
//广搜求最短路径长度
int BFS();
//深搜求最短路径条数
void DFS(int x, int y, int len);
int main()
{
//求最短路径长度
ShortestPathLength = BFS();
if (ShortestPathLength == -1) //没路可走时
{
printf("No Solution!\n");
}
//求最短路径条数及输出所有的最短路径
ShortestPahtNumber = 0;
sx.push(p);
sy.push(q);
DFS(p, q, 0);
//输出结果
printf("最短路径长度: %d\n\n", ShortestPathLength);
printf("最短路径条数: %d\n\n", ShortestPahtNumber);
}
int BFS()
{
queue<int> qx; //存横坐标的队列
queue<int> qy; //存纵坐标的队列
queue<int> qlen; //存长度的队列
int xa, ya; //当前节点坐标
int length; //到达当前节点长度
qx.push(p);
qy.push(q);
qlen.push(0);
mazeBfs[p][q] = 1;
while (!qx.empty())
{
if ((qx.front()==r) && (qy.front()==s)) //判断是否到达小鼠b
{
return qlen.front();
}
//临时保存队头值
int xx, yy ,ll;
xx = qx.front();
yy = qy.front();
ll = qlen.front();
//保存完之后,出队
qx.pop();
qy.pop();
qlen.pop();
for (int i=0; i<8; i++)
{
//算第i方向上的新值
xa = xx + coordinate[i][0];
ya = yy + coordinate[i][1];
length = ll;
//新的点在迷宫内,且没有走过
if ((xa>=1) && (xa<=n) && (ya>=1) && (ya<=m) && (mazeBfs[xa][ya]==0))
{
//入队
qx.push(xa);
qy.push(ya);
length += 1;
qlen.push(length);
//标记新点
mazeBfs[xa][ya] = 1;
}
}
}
return -1; //如果没有路,返回0
}
void DFS(int x, int y, int len)
{
if ((x==r) && (y==s) && (len==ShortestPathLength)) //找到一条最短路径
{
ShortestPahtNumber++;
return ;
}
for (int i=0; i<8; i++)
{
int xx, yy;
xx = x + coordinate[i][0];
yy = y + coordinate[i][1];
if ((xx>=1) && (xx<=n) && (yy>=1) && (yy<=m) && (mazeDfs[xx][yy]==0))
{
sx.push(xx);
sy.push(yy);
mazeDfs[xx][yy] = 1;
DFS(xx, yy, len+1);
//回溯
sx.pop();
sy.pop();
mazeDfs[xx][yy] = 0;
}
}
}