题解
【基础】迷宫的所有路径
1 条题解
-
0
#include <bits/stdc++.h> using namespace std; int n; int cnt=0; // 记录路径数 bool f[10][10]; int a[50][2]; // 存放所有走过的路径的x,y坐标 a[i][0] a[i][1] // 右 下 左 上 int fx[4] = {0, 1, 0, -1}; int fy[4] = {1, 0, -1, 0}; // 打印路径 ,k是路径部署,即储存a数组元素的个数 void print(int k){ cnt++; cout << cnt << ":"; for(int i=1;i<=k;i++){ if(i != k){ cout << a[i][0] << "," << a[i][1] << "->"; } else { cout << a[i][0] << "," << a[i][1] << endl; } } } // k代表当前走的步数,即 向二维数组a中填值的一维下标 void dfs(int k){ // 遍历4个方向 for(int i=0;i<4;i++){ int tx = a[k-1][0] + fx[i]; int ty = a[k-1][1] + fy[i]; // 在范围内,且没走过 if(tx >= 1 && tx <= n && ty >= 1 && ty <= n && !f[tx][ty]){ // 标记走过 f[tx][ty] = true; // 储存该点坐标 a[k][0] = tx; a[k][1] = ty; // 代表到达终点,输出路径 if(tx == n && ty == n) { print(k); } else { // 继续往下走 dfs(k+1); } // 回溯,还原标记 f[tx][ty] = false; } } } int main() { cin >> n; a[1][0] = 1; a[1][1] = 1; f[1][1] = true; // 标记起始点(1,1)走过 dfs(2); // 从第2步开始走 return 0; }
- 1