1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| #include <bits/stdc++.h> using namespace std; int n,m,f[1005][1005],g[1005][1005],h[1005][1005],k[1005][1005]; char c; bool v[1005][1005],can[1005][1005]; int check(int i,int j){ if (can[i-1][j]&&can[i][j-1])return 2; else if (can[i-1][j])return 1; else return 0; } int main(){ cin>>n>>m; for (int i=1;i<=n;i++) for (int j=1;j<=m;j++){ cin>>c; if (c=='#')v[i][j]=1,can[i][j]=0; } can[1][1]=!v[1][1]; for(int i=1;i<=n;i++) for(int j=1;j<=m;j++){ can[i][j]|=can[i-1][j]|can[i][j-1]; if (v[i][j])can[i][j]=0; } if (!can[n][m])return !printf ("-1"); for (int i=2;i<=n;i++) for (int j=2;j<=m;j++)f[i][j]=-(1<<11),g[i][j]=1<<11; for (int i=1;i<=n;i++)h[i][1]=k[i][1]=1; for (int i=2;i<=n;i++) for (int j=2;j<=m;j++)if (can[i][j]){ if (f[i-1][j]+(h[i-1][j]!=1)>f[i][j-1]+(h[i][j-1]!=0)&&(can[i-1][j]))f[i][j]=f[i-1][j]+(h[i-1][j]!=1),h[i][j]=1; else if (f[i-1][j]+(h[i-1][j]!=1)==f[i][j-1]+(h[i][j-1]!=0))f[i][j]=f[i-1][j]+(h[i-1][j]!=1),h[i][j]=check(i,j); else if (can[i][j-1])f[i][j]=f[i][j-1]+(h[i][j-1]!=0),h[i][j]=0; if (g[i-1][j]+(k[i-1][j]==0)<g[i][j-1]+(k[i][j-1]==1)&&(can[i-1][j]))g[i][j]=g[i-1][j]+(k[i-1][j]==0),k[i][j]=1; else if (g[i-1][j]+(k[i-1][j]==0)==g[i][j-1]+(k[i][j-1]==1))g[i][j]=g[i-1][j]+(k[i-1][j]==0),k[i][j]=check(i,j); else if (can[i][j-1])g[i][j]=g[i][j-1]+(k[i][j-1]==1),k[i][j]=0; } if (f[n][m]>0)printf ("%d %d\n",f[n][m],g[n][m]); else putchar('-'),putchar('1'); }
|