2010年顶嵌杯决赛B题

http://poj.org/problem?id=3984

本题其实比较简单就是用BFS搜索算法就可以了,不过本题还要考虑保存最短路径,

思路如下:

1.要找出最短路径

2.标志每一个节点的父节点

3.倒置输出即可

其中的p[i][j]表示节点i,j的父节点

#include<stdio.h> #include<string.h> #include<math.h> #include<stdlib.h> typedef struct Node{ int x,y; }Parent; Parent p[5][5],q[30]; int mat[5][5],visit[5][5]; int check(int x,int y) { if(x>=0 && x<5 && y>=0 && y<5) return 1; else return 0; } void dfs(int i, int j) { int dx[4]={-1,0,1,0}; int dy[4]={0,1,0,-1}; int x, y, k, x0, y0; int head, tail; head = 0; tail = 0; q[tail].x = i; q[tail++].y = j; visit[i][j] = 1; p[i][j].x = -1; p[i][j].y = -1; while(head<=tail) { x = q[head].x; y = q[head].y; for(k=0; k<4; k++) { x0 = x + dx[k]; y0 = y + dy[k]; if(check(x0,y0) && mat[x0][y0]==0 && visit[x0][y0]==0) { visit[x0][y0] = 1; p[x0][y0].x = x; p[x0][y0].y = y; if(x0 == 4 && y0 == 4) return; q[tail].x = x0; q[tail++].y = y0; } } head++; } } int main() { // freopen("in.txt", "r", stdin); int i, j, x; int ans = 1; int path[30][2]; for(i=0; i<30; i++) { q[i].x = -1; q[i].y = -1; path[i][0] = -1; path[i][1] = -1; } for(i=0; i<5; i++) { for(j=0; j<5; j++) { visit[i][j] = 0; p[i][j].x = -1; p[i][j].y = -1; scanf("%d", &mat[i][j]); } } dfs(0,0); i = 4; j = 4; while(p[i][j].x != -1 && p[i][j].y != -1) { path[ans][0] = i; path[ans++][1] = j; x = i; i = p[i][j].x; j = p[x][j].y; } path[ans][0] = 0; path[ans][1] = 0; for(i=ans; i>0; i--) printf("(%d, %d)/n",path[i][0],path[i][1]); return 0; }

你可能感兴趣的:(算法,struct,XP,Path,2010)