牛客练习赛58 D 迷宫
思想:
dp[i][j]代表到达坐标(i,j)这个位置最少需要转换成障碍格子的数目;
代码:
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxn = 1005;
char a[maxn][maxn];
int dp[maxn][maxn];
int main(){
int n,m;
cin>>n>>m;
for(int i=1;i<=n;i++){
getchar();
for(int j=1;j<=m;j++)
scanf("%c",&a[i][j]);
}
if(a[1][1]=='1'){
cout<<"-1"<<endl;
return 0;
}
memset(dp,inf,sizeof(dp));
dp[1][1] = 0;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
if(a[i][j]=='1') continue;
if(a[i][j+1]=='0')
dp[i][j+1] = min(dp[i][j+1],dp[i][j]);
if(a[i][j+1]!='0'&&a[i+1][j]=='0')//这里判断不为‘0’,是可以同时满足当a[i][j+1]=='1'||j==m的情况
dp[i+1][j] = min(dp[i+1][j],dp[i][j]);
if(a[i][j+1]=='0'&&a[i+1][j]=='0')
dp[i+1][j] = min(dp[i+1][j],dp[i][j]+1);
}
}
if(dp[n][m]!=inf) cout<<dp[n][m]<<endl;
else cout<<"-1"<<endl;
return 0;
}