题解 | #迷宫问题#
迷宫问题
https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
#include <stdio.h>
int map[11][11];//地图
int n, m; //地图规模
int trace[101][2];//记录路径
//允许的方向
int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};
void dfs(int x, int y, int cnt) { //cnt指走了几步路
if (map[n - 1][m - 1] == 2) {
for (int i = 0; i < cnt; i++) {
printf("(%d,%d)\n", trace[i][0], trace[i][1]);
}
return;
}
//四个方向
for (int i = 0; i < 4; i++) {
int xx = dx[i] + x;
int yy = dy[i] + y;
//边界
if (xx >= 0 && yy >= 0 && xx < n && yy < m && map[xx][yy] == 0) {
map[xx][yy] = 2;
trace[cnt][0] = xx;
trace[cnt][1] = yy;
dfs(xx, yy, cnt + 1);
map[xx][yy] = 0;
}
}
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
scanf("%d", &map[i][j]);
}
}
//0-没走过 1-墙 2-可达
trace[0][0] = trace[0][1] = 0;
map[0][0] = 2;
dfs(0, 0, 1);
return 0;
}
查看13道真题和解析
快手公司福利 1244人发布