这有一个迷宫,有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)。)
Input
第一行输入一个整数n(0<n<=100),表示有n组测试数据;
随后n行,每行有四个整数a,b,c,d(0<=a,b,c,d<=8)分别表示起点的行、列,终点的行、列。
随后n行,每行有四个整数a,b,c,d(0<=a,b,c,d<=8)分别表示起点的行、列,终点的行、列。
Output
输出最少走几步。
Sample Input
2 3 1 5 7 3 1 6 7
Sample Output
1211
广搜:
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
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 b[4]= {-1,1,0,0}; //2个数组组成方向
int c[4]= {0,0,-1,1};
int visit[9][9];
struct node
{
int x,y;
int step;
};
queue<node> Q;//定义队列
int bfs(int x1,int y1,int x2,int y2)
{
while(!Q.empty())//队列不为空
Q.pop();//队列不是空的就清空
int i,s,t;
node e= {x1,y1,0}; //定义第一个坐标,步数为0
Q.push(e);//输入队列
visit[x1][y1]=1;//标记已经走过的
while(!Q.empty())//队列不为空
{
e=Q.front();//返回第一个元素(队顶元素)
Q.pop();//清空
if(e.x==x2 && e.y==y2)
{
return e.step;
}
for(i=0; i<4; i++)
{
s=e.x+b[i];
t=e.y+c[i];
if(s>=0 && s<=8 && t>=0 && t<=8 && !visit[s][t] && a[s][t]==0)//判断条件
{
node e1= {s,t,e.step+1};
Q.push(e1);
visit[s][t]=1;
}
}
}
return -1;
}
int main()
{
int k,s,x1,x2,y1,y2;
scanf("%d",&s);
while(s--)
{
scanf("%d %d %d %d",&x1,&y1,&x2,&y2);
memset(visit,0,sizeof(visit));
k=bfs(x1,y1,x2,y2);
printf("%d\n",k);
}
return 0;
}
深搜:
#include<stdio.h>
#include<string.h>
#define min(a,b) (a<b?a:b)
int vis[9][9];
int c,d,s;
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,//2
1,0,1,0,1,1,0,1,1,
1,0,0,0,0,1,0,0,1,//4
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,
};
void dfs(int x,int y,int step)//深搜---
{
if(step>s||vis[x][y]||a[x][y])//接着搜下去也得不到最优解||走过||能走
return ;
if(x==c&&y==d)
{
s=min(step,s);
}
vis[x][y]=1;
dfs(x-1,y,step+1);
dfs(x+1,y,step+1);
dfs(x,y-1,step+1);
dfs(x,y+1,step+1);
vis[x][y]=0;
}
int main()
{
int n;
scanf("%d",&n);
while(n--)
{
int q,w;
memset(vis,0,sizeof(vis));
scanf("%d%d%d%d",&q,&w,&c,&d);
s=0xffffff;//无穷大
dfs(q,w,0);
printf("%d\n",s);
}
}
ps:第一道搜索题。