题面
最少步数问题,可以准备一个步数数组,记录从出发点到每个点至少多少步,然后不断替换最少步数,知道找出最优解。
#include <bits/stdc++.h>
using namespace std;
char a[50][50];
int fx[5] = {0 , 0 , 1 , 0 , -1} , fy[5] = {0 , 1 , 0 , -1 , 0};
int d[50][50] , n , m;
void dfs( int x , int y , int dep ){
d[x][y] = dep;
int tx , ty;
for ( int i = 1 ; i <= 4 ; i++ ){
tx = x + fx[i];
ty = y + fy[i];
if ( a[tx][ty] == '.' && dep + 1 < d[tx][ty] )
dfs(tx , ty , dep+1);
}
}
int main(){
scanf("%d%d" , &n , &m);
for ( int i = 1 ; i <= n ; i++ )
for ( int j = 1 ; j <= m ; j++ ){
cin >>a[i][j];
d[i][j] = INT_MAX;
}
dfs(1 , 1 , 1);
printf("%d" , d[n][m]);
return 0;
}
这题还有个变种,就是给定起点和终点,求最少步数(要注意第一次到终点不一定是最优解,所以要return一下)
#include <bits/stdc++.h>
using namespace std;
char a[110][110];
int n , m , s1 ,s2 , e1 , e2 , d[110][110];
int fx[5] = {0 , 0 , 1 , 0 , -1},fy[5] = {0 , 1 , 0 , -1 , 0};
void dfs(int x , int y , int k){
d[x][y] = k;
if(x == e1 && y == e2){
return;
}
int tx , ty;
for( int i = 1 ; i <= 4 ; i++ ){
tx = x + fx[i];
ty = y + fy[i];
if( (a[tx][ty] == '.' || a[tx][ty] == 'T') && k + 1 < d[tx][ty] )
dfs(tx , ty , k+1);
}
}
int main(){
scanf("%d%d" , &n , &m);
for ( int i = 1 ; i <= n ; i++ )
for ( int j = 1 ; j <= m ; j++ ){
cin >> a[i][j];
if( a[i][j] == 'S' ){
s1 = i;
s2 = j;
}
else if(a[i][j] == 'T'){
e1 = i;
e2 = j;
}
d[i][j] = INT_MAX;
}
dfs(s1 , s2 , 0);
printf("%d" , d[e1][e2]);
return 0;
}
迷宫的第一条出路
将路径的下标K作为递归参数,这样递归后退时K也会后退,从而覆盖原来的元素
代码
#include <bits/stdc++.h>
using namespace std;
int n , r[410][3];
int fx[5] = {0 , 0 , -1 , 0 , 1},fy[5] = {0 , -1 , 0 , 1 , 0};
char a[35][35];
void print(int k){
for ( int i = 1 ; i <= k ; i++ ){
printf("(%d,%d)" , r[i][1] , r[i][2]);
if( i != k )
printf("->");
}
}
void dfs( int x , int y , int k){
a[x][y] = '1';
r[k][1] = x;
r[k][2] = y;
if ( x == n && y == n ){
print(k);
exit(0);
}
int tx , ty;
for ( int i = 1 ; i <= 4 ; i++ ){
tx = x + fx[i];
ty = y + fy[i];
if(a[tx][ty] == '0')
dfs(tx , ty , k+1);
}
}
int main(){
scanf("%d" , &n);
for ( int i = 1 ; i <= n ; i++ )
for ( int j = 1 ; j <= n ; j++ )
cin >> a[i][j];
dfs(1,1,1);
return 0;
}