这有一个迷宫,有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
一AC,果然痛快!好久没有这种感觉了!
代码如下:
#include<stdio.h> #include<string.h> #include<queue> #define mem(a) memset(a,0,sizeof(a)) using namespace std; typedef struct{ int x,y; int step; }node; node begin,end; int visit[1000100]; int b[2][4]={0,1,0,-1,1,0,-1,0};//前进的横纵坐标变化 int hash(node u) { return u.x*100+u.y;//标记 该节点 } int find(node u,node v) { return u.x==v.x&&u.y==v.y; } int main() { int i,j; int t; scanf("%d",&t); while(t--) { mem(visit); 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 }; scanf("%d%d",&begin.x,&begin.y); begin.step=0; scanf("%d%d",&end.x,&end.y); queue<node>q; q.push(begin); visit[hash(begin)]=1; map[begin.x][begin.y]=1; while(!q.empty()) { node u=q.front(); q.pop(); if(find(u,end)) { printf("%d\n",u.step); break; } for(int i=0;i<4;++i) { if(map[u.x+b[0][i]][u.y+b[1][i]]==0) { map[u.x+b[0][i]][u.y+b[1][i]]=1; node v=u; v.x+=b[0][i]; v.y+=b[1][i]; v.step++; if(!visit[hash(v)]) { visit[hash(v)]=1; q.push(v); } } } } while(!q.empty()) q.pop(); } return 0; }
原文地址:http://blog.csdn.net/ice_alone/article/details/44961791