标签:
这有一个迷宫,有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
自己搜索不太好,参考代码网址:54楼
http://acm.nyist.net/JudgeOnline/talking.php?pid=58
#include<iostream> #include<queue> #include<string.h> using namespace std; int num[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 visit[9][9]; struct point { int x; int y; int step; }; void bfs(int startx,int starty,int endx,int endy) { queue<point>q; point now,next; int x[4]={0,1,0,-1}; int y[4]={1,0,-1,0}; int k,exit=0; now.step=0; now.x=startx; now.y=starty; q.push(now); while(!q.empty()) { next=q.front(); q.pop(); if(next.x==endx &&next.y==endy) { exit=1; break; } for(k=0;k<4;k++) { now.x=next.x+x[k]; now.y=next.y+y[k]; if(!visit[now.x][now.y] &&now.x>=0 &&now.x<9 &&now.y>=0 &&now.y<9 &&num[now.x][now.y]==0) { visit[now.x][now.y]=1; now.step=next.step+1; q.push(now); } } } if(exit) cout<<next.step<<endl; else cout<<-1<<endl; } int main() { int a,b,c,d,T; cin>>T; while(T--) { cin>>a>>b>>c>>d; memset(visit,0,sizeof(visit)); bfs(a,b,c,d); } return 0; }
标签:
原文地址:http://blog.csdn.net/zuguodexiaoguoabc/article/details/45058103