题目http://115.159.40.116/problem_show.php?pid=4670
二维地图最短路问题 广搜,这个题深搜也可以,先写个广搜吧
#include<iostream>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
int si,sj,di,dj;
int map[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
};
bool vis[9][9];//用于标记走过的路
int go[4][2]= {0,1,0,-1,1,0,-1,0};//四个方向
struct node
{
int si,sj,ans;//结构体用来储存走到的位置和步数
};
int bfs(int si,int sj)
{
node now,next;
queue<node>s;
now.si=si,now.sj=sj,now.ans=0;//首先队列存入入口·
s.push(now);
while(!s.empty())
{
now=s.front();
if(now.si==di&&now.sj==dj)//到达出口返回步数
return now.ans;
for(int i=0; i<4; i++)//四个方向进行广搜
{
int m=now.si+go[i][0],n=now.sj+go[i][1];
if(m>=0&&n>=0&&m<9&&n<9&&!map[m][n]&&!vis[m][n])
{
vis[m][n]=1;
next.si=m,next.sj=n,next.ans=now.ans+1;
s.push(next);
}
}
s.pop();//已经用过的出队列
}
}
int main()
{
int n;
cin>>n;
while(n--)
{
memset(vis,0,sizeof(vis));
cin>>si>>sj>>di>>dj;
cout<<bfs(si,sj)<<endl;
}
return 0;
}
下面是这个题深搜的做法
#include<stdio.h>
int map[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 si,sj,di,dj,minans;//起点,终点,和最小步数
int go[4][2]= {{0,1},{0,-1},{1,0},{-1,0}};//四个方向
void dfs(int si,int sj,int ans)
{
int i=0;
if(si<0||sj<0||si>8||sj>8)//如果越界就返回
return;
if(si==di&&sj==dj)//到达终点
{
if(minans>ans)//如果比minans还小就记录下来
minans=ans;
}
for(i=0; i<4; i++)//深搜
{
if(map[si+go[i][0]][sj+go[i][1]]==0)
{
map[si+go[i][0]][sj+go[i][1]]=1;//走过的路进行标记
dfs(si+go[i][0],sj+go[i][1],ans+1);//接着深搜
map[si+go[i][0]][sj+go[i][1]]=0;//恢复标记过的路
}
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
minans=10010;
scanf("%d%d%d%d",&si,&sj,&di,&dj);//起点和终点
dfs(si,sj,0);//深搜入口,哈哈哈哈
printf("%d
",minans);//输出最小步数
}
return 0;
}