1、http://poj.org/problem?id=3984
2、题目大意:给定一个迷宫,其中0表示可以走,1表示有墙,求从起始点到最后一个点的最短距离,注意路径用prev数组标记即可,逆序输出即可
3、题目:
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 6166 | Accepted: 3573 |
Description
int maze[5][5] = { 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, };
Input
Output
Sample Input
0 1 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 1 1 0 0 0 0 1 0
Sample Output
(0, 0) (1, 0) (2, 0) (2, 1) (2, 2) (2, 3) (2, 4) (3, 4) (4, 4)
4、ac代码:
#include<stdio.h> #include<string.h> int map[5][5]; int dir[4][2]={0,1,1,0,0,-1,-1,0}; struct node { int x; int y; int step; }a[30]; struct node1 { int px; int py; }prev[6][6]; int bfs() { memset(prev,-1,sizeof(prev)); a[0].x=0; a[0].y=0; a[0].step=0; node cur,change; int start=0,end=1; while(start<end) { cur=a[start++]; if(cur.x==4 && cur.y==4) return cur.step; for(int i=0;i<4;i++) { int tx=cur.x+dir[i][0]; int ty=cur.y+dir[i][1]; if(tx>=0 && tx<5 && ty>=0 && ty<5 && map[tx][ty]==0) { map[tx][ty]=1; change.x=tx; change.y=ty; change.step=cur.step+1; a[end++]=change; prev[tx][ty].px=cur.x; prev[tx][ty].py=cur.y; } } } } int main() { for(int i=0;i<5;i++) { for(int j=0;j<5;j++) scanf("%d",&map[i][j]); } int sum=bfs(); //printf("*%d\n",sum); node ans[30]; int ex=4,ey=4; for(int i=0;i<sum;i++) { ans[i].x=prev[ex][ey].px; ans[i].y=prev[ex][ey].py; ex=ans[i].x; ey=ans[i].y; } for(int i=sum-1;i>=0;i--) { printf("(%d, %d)\n",ans[i].x,ans[i].y); } printf("(4, 4)\n"); return 0; }