这有一个迷宫,有0~8行和0~8列:
1,1,1,1,1,1,1,1,1
1,0,0,1,0,0,1,0,1
1,0,0,1,1,0,0,0,1
1,0,1,0,1,1,0,1,1
1,0,0,0,0,1,0,0,1
1,1,0,1,0,1,0,0,1
1,1,0,1,0,1,0,0,1
1,1,0,1,0,0,0,0,1
1,1,1,1,1,1,1,1,1
0表示道路,1表示墙。
现在输入一个道路的坐标作为起点,再如输入一个道路的坐标作为终点,问最少走几步才能从起点到达终点?
(注:一步是指从一坐标点走到其上下左右相邻坐标点,如:从(3,1)到(4,1)。)
2
3 1 5 7
3 1 6 7
12
11
**搜索问题本题路线比较单一DFS BFS 都可以
1.BFS
#include
#include
using namespace std;
int map1[9][9]={
{1,1,1,1,1,1,1,1,1},
{1,0,0,1,0,0,1,0,1},
{1,0,0,1,1,0,0,0,1},
{1,0,1,0,1,1,0,1,1},
{1,0,0,0,0,1,0,0,1},
{1,1,0,1,0,1,0,0,1},
{1,1,0,1,0,1,0,0,1},
{1,1,0,1,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1},
};
int map[9][9];
int gonext[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
int strx,stry,endx,endy;
bool isfind;
struct Pos{
int x,y,s;
} p,pt;
queue que;
void inist()
{
for(int i=0;i<9;i++)
for(int j=0;j<9;j++)
map[i][j] = map1[i][j];
}
int main()
{
int T,i,j;
cin>>T;
while(T--)
{
cin>>strx>>stry>>endx>>endy;
if(strx==endx && stry == endy)
{
cout<<"0"<
下面是注释
#include
#include
#include
#include
#include
using namespace std;
int map1[9][9]={ //用来初始化的
{1,1,1,1,1,1,1,1,1},
{1,0,0,1,0,0,1,0,1},
{1,0,0,1,1,0,0,0,1},
{1,0,1,0,1,1,0,1,1},
{1,0,0,0,0,1,0,0,1},
{1,1,0,1,0,1,0,0,1},
{1,1,0,1,0,1,0,0,1},
{1,1,0,1,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1},
};
int map[9][9];//用来查找
int gonext[4][2]={{1,0},{0,1},{-1,0},{0,-1}};//用来移动坐标
int strx,stry,endx,endy;//起点终点
bool isfind;//标记元素
struct Pos{//结构体表示坐标 ,s表示步数
int x,y,s;
} p,pt;
queue que;//查找队列
void inist()//初始话map,每次查找都要重新初始化
{
for(int i=0;i<9;i++)
for(int j=0;j<9;j++)
map[i][j] = map1[i][j];
}
int main()
{
int T,i,j;
cin>>T;
while(T--)
{
cin>>strx>>stry>>endx>>endy;
if(strx==endx && stry == endy)//如果起点等于终点
{
cout<<"0"<
回头再试试DFS
2,DFS
dfs不算难
#include
#include
using namespace std;
int map1[9][9]={
{1,1,1,1,1,1,1,1,1},
{1,0,0,1,0,0,1,0,1},
{1,0,0,1,1,0,0,0,1},
{1,0,1,0,1,1,0,1,1},
{1,0,0,0,0,1,0,0,1},
{1,1,0,1,0,1,0,0,1},
{1,1,0,1,0,1,0,0,1},
{1,1,0,1,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1},
};
int map[9][9];
int gonext[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
int strx,stry,endx,endy;
int themin;
void inist()
{
for(int i=0;i<9;i++)
for(int j=0;j<9;j++)
map[i][j] = map1[i][j];
}
void dfs(int x,int y,int step)
{
int tx,ty;
if(x==endx&&y==endy)//如果找到就退出
{
if(step>T;
while(T--)
{
cin>>strx>>stry>>endx>>endy;
themin = 999999;//初始化下
inist();
map[strx][stry] = 1;
dfs(strx,stry,0);
cout<