定义一个二维数组:
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)
问题分析:简单的DFS,多加一步记录其走过的路径
AC代码:
#include<iostream>
#include<cstring>
#include<stdio.h>
using namespace std;
int m[30][30],vis[30][30],mi=99999999,xs[30],ys[30],xe[30],ye[30],tx,ty;
int n[4][2] = { 1,0,0,1,-1,0,0,-1 };
void dfs(int x, int y, int step)
{if (x == 4 && y == 4){if (mi > step)mi = step;for (int i = 0; i < step; i++){xe[i] = xs[i];ye[i] = ys[i];}return;}for (int i = 0; i < 4; i++){tx = x + n[i][0];ty = y + n[i][1];if (tx > 4 || ty > 4 || tx < 0 || ty < 0)continue;if (vis[tx][ty] != 1&&m[tx][ty]!=1){vis[tx][ty] = 1;xs[step] = tx;ys[step] = ty;dfs(tx, ty, step + 1);vis[tx][ty] = 0;}}}
int main()
{for (int i = 0; i < 5; i++)for (int j = 0; j < 5; j++)cin >> m[i][j];dfs(0, 0, 0);printf("(0, 0)\n");for (int i = 0; i < mi; i++)printf("(%d, %d)\n", xe[i], ye[i]);
}