时间限制:3000 ms | 内存限制:65535 KB
难度:4
输入
第一行输入一个整数n(0<n<=100),表示有n组测试数据;
随后n行,每行有四个整数a,b,c,d(0<=a,b,c,d<=8)分别表示起点的行、列,终点的行、列。
输出
输出最少走几步。
样例输入
2
3 1 5 7
3 1 6 7
样例输出
12
11
来源
上传者
描述
这有一个迷宫,有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)。)
思路:随缘搜索!
1)【bfs】:
#include<bits/stdc++.h>
#include<string.h>
#include<queue>
using namespace std;
const int maxn = 10;
int vis[maxn][maxn];
int a[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 x1,y11,x2,y2,ans;
int dir[4][2]={1,0,-1,0,0,1,0,-1};
struct node{
int x,y,step;
bool friend operator < (node a,node b)
{
return a.step > b.step;
}
};
bool check(int x,int y)
{
if(x>=0 && x<=8 && y>=0 && y<=8)
return true;
return false;
}
int bfs(int x,int y)
{
priority_queue<node>que;
node e1,e2;
e1.x = x,e1.y = y,e1.step = 0;
que.push(e1);
vis[x][y]=1;
ans=0;
while(!que.empty())
{
e1 = que.top();
que.pop();
if(e1.x == x2 && e1.y == y2)
{
ans = e1.step;
break;
}
for(int i=0;i<4;i++)
{
e2.x = e1.x + dir[i][0];
e2.y = e1.y + dir[i][1];
if(a[e2.x][e2.y]==0 && !vis[e2.x][e2.y] && check(e2.x,e2.y))
{
e2.step = e1.step + 1;
que.push(e2);
vis[e2.x][e2.y]=1;
}
}
}
if(ans==0)
cout<<0<<endl;
else
cout<<ans<<endl;
}
int main()
{
int t;
cin>>t;
while(t--)
{
memset(vis,0,sizeof(vis));
cin>>x1>>y11>>x2>>y2;
bfs(x1,y11);
}
return 0;
}
2) 【dfs】:
#include<bits/stdc++.h>
#include<string.h>
#include<queue>
using namespace std;
const int maxn = 10;
int a[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 x1,y11,x2,y2,ans,sum;
int dir[4][2]={1,0,-1,0,0,1,0,-1};
void dfs(int x,int y,int ans)
{
if(x == x2 && y == y2)
{
if(ans<sum)
sum=ans;
return ;
}
else
{
for(int i=0;i<4;i++)
{
int nx = x + dir[i][0];
int ny = y + dir[i][1];
if(a[nx][ny]==0 && ans+1 <sum)
{
a[nx][ny]=1;
dfs(nx,ny,ans+1);
a[nx][ny]=0;
}
}
}
}
int main()
{
ios::sync_with_stdio(false);
int t;
cin>>t;
while(t--)
{
ans=0;
sum=0x3f3f3f3f;
cin>>x1>>y11>>x2>>y2;
a[x1][y11]=1;
dfs(x1,y11,ans);
cout<<sum<<endl;
a[x1][y11]=0;
}
return 0;
}