K
来源:互联网 发布:用友软件投标书 编辑:程序博客网 时间:2024/06/02 08:25
https://vjudge.net/contest/65959#problem/K
题目大意
定义一个二维数组:
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,
};
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
Input
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。
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)
解题思路
一道典型的BFS题,因为这次不是让你求最少走的步数,而是求它的路径,所以要结合DFS,用BFS正向让它到达最右下角,再用DFS递归求出它从前到后的路径。
具体BFS还是按照套路做(四个方向,一个二维结构体数组来记录当前位置),重点在DFS上,我总结了一句话叫 “用当下记录过去”, 怎么解释???就是二维结构体数组, 用当下的位置作为它的下标, 用它的值代表上次的位置(具体看代码), 这样可以通过递归反向的找到从最后一个位置到第一个位置的路径。
代码
# include <stdio.h># include <queue># include <string.h>using namespace std;int dir[4][2] = { {1,0}, {-1,0}, {0,-1}, {0,1}};int num[5][5];struct node{ int x, y;}v[5][5]; void DFS(int x, int y){ if(x == 0 && y ==0) { return; } DFS(v[x][y].x, v[x][y].y); printf("(%d, %d)\n",v[x][y].x, v[x][y].y);}void BFS(node s){ node t, q; queue<node>Q; Q.push(s); while(Q.size()) { q = Q.front(); Q.pop(); if(q.x == 4 && q.y == 4) { DFS(q.x, q.y); printf("(%d, %d)\n",q.x,q.y); return; } for(int i = 0; i<4; i++) { t = q;//关键之笔,让同一个位置走四次不同的方向 t.x += dir[i][0]; t.y += dir[i][1]; if(t.x >=0 && t.y >=0 && t.x <5 && t.y <5 && num[t.x][t.y] == 0) { v[t.x][t.y].x = q.x; v[t.x][t.y].y = q.y; num[t.x][t.y] = 1; Q.push(t); } } }}int main(void){ int i, j; for(i = 0; i<5; i++) { for(j = 0; j<5; j++) { scanf("%d",&num[i][j]); } } memset(v, 0, sizeof(v)); node s; s.x = 0; s.y = 0; BFS(s); return 0; }
0 0