题面
题目描述
已知一N×N 的迷宫,允许往上、下、左、右四个方向行走,且迷宫中没有任何障碍,所有的点都可以走。
现请你按照右、下、左、上顺序进行搜索,找出从左上角到右下角的所有路径。
输入
输入一个整数 N(N≤5)代表迷宫的大小。
输出
按右、下、左、上搜索顺序探索迷宫,输出从左上角 (1,1) 点走到右下角 (N,N) 点的所有可能的路径。
样例
输入
3输出
1:1,1->1,2->1,3->2,3->3,3 2:1,1->1,2->1,3->2,3->2,2->3,2->3,3 3:1,1->1,2->1,3->2,3->2,2->2,1->3,1->3,2->3,3 4:1,1->1,2->2,2->2,3->3,3 5:1,1->1,2->2,2->3,2->3,3 6:1,1->1,2->2,2->2,1->3,1->3,2->3,3 7:1,1->2,1->2,2->2,3->3,3 8:1,1->2,1->2,2->3,2->3,3 9:1,1->2,1->2,2->1,2->1,3->2,3->3,3 10:1,1->2,1->3,1->3,2->3,3 11:1,1->2,1->3,1->3,2->2,2->2,3->3,3 12:1,1->2,1->3,1->3,2->2,2->1,2->1,3->2,3->3,3
典型回溯题,因为能走四个方向,所以要标记走过的路再撤销
解法一:有X,Y,K三个函数
#include <bits/stdc++.h>
using namespace std;
int n , r[30][3] , c=0;
int fx[5] = {0 , 0 , 1 , 0 , -1} , fy[5] = {0 , 1 , 0 , -1 , 0};
bool f[10][10];
void print(int f){
c++;
printf("%d:" , c);
for ( int i = 1 ; i < f ; i++ )
printf("%d,%d->" , r[i][1] , r[i][2]);
printf("%d,%d\n" , n , n);
}
void dfs(int x , int y , int k){
r[k][1] = x;
r[k][2] = y;
if ( x == n && y == n ){
print(k);
return;
}
int tx , ty;
for ( int i = 1 ; i <= 4 ; i++ ){
tx = x + fx[i];
ty = y + fy[i];
if( tx >= 1 && tx <= n && ty >= 1 && ty <= n && f[tx][ty] == false){
f[tx][ty] = true; //回溯
dfs(tx , ty , k+1);
f[tx][ty] = false; //回溯
}
}
}
int main(){
scanf("%d" , &n);
f[1][1] = true;
dfs(1,1,1);
return 0;
}
解法二:用r数组存储的数据
#include <bits/stdc++.h>
using namespace std;
int n , r[30][3] , c=0;
int fx[5] = {0 , 0 , 1 , 0 , -1} , fy[5] = {0 , 1 , 0 , -1 , 0};
bool f[10][10];
void print(int f){
c++;
printf("%d:" , c);
for ( int i = 1 ; i < f ; i++ )
printf("%d,%d->" , r[i][1] , r[i][2]);
printf("%d,%d\n" , n , n);
}
void dfs(int k){
int tx , ty;
for ( int i = 1 ; i <= 4 ; i++ ){
tx = r[k-1][1] + fx[i];
ty = r[k-1][2] + fy[i];
if( tx >= 1 && tx <= n && ty >= 1 && ty <= n && f[tx][ty] == false){
f[tx][ty] = true; //保存现场状态
r[k][1] = tx;
r[k][2] = ty;
if ( tx == n && ty == n ) print(k);
else dfs(k+1);
f[tx][ty] = false; //恢复
}
}
}
int main(){
scanf("%d" , &n);
f[1][1] = true , r[1][1] = 1 , r[1][2] = 1;
dfs(2);
return 0;
}