解题思路:只需两次dfs即可,第一次找到第一条(1,1)到(n,m)的路径,并且路径上的点mark掉;第二次dfs就是判断是否还有(1,1)到(n,m)的路径。
- (1)如果第一次dfs没有搜索到路径,ans=0;
- (2)如果第二次没有搜索到路径,ans=1;
- (3)如果第二次搜索到了路径,ans=2;
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<vector>
#include<cmath>
#include<string>
#include<map>
#include<queue>
using namespace std;
typedef long long ll;
const ll maxn=1000000+5;
string s[maxn];
//由于直接开数组(maxn*maxn)实在太大,所以根据输入的n,m用vector的resize函数动态申请
vector<bool > vis[maxn];
vector<bool > mark[maxn];
ll n,m;
bool dfs(int x,int y){
if(x==n&&y==m)return true;
if(x>n||y>m||s[x-1][y-1]=='#'||vis[x][y]||mark[x][y])return false;
vis[x][y]=true;
bool flag=dfs(x+1,y);//先往下走
if(!flag)flag=dfs(x,y+1);//往下走行不通在向右走
if(flag)mark[x][y]=true;//判断在此点能否有通路,有,则mark
return flag;
}
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++){
cin>>s[i-1];
vis[i].resize(m+1);//动态申请
mark[i].resize(m+1);
}
bool flag=dfs(1,1);//第一次dfs
if(!flag){
cout<<0<<endl;
}
else {
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
vis[i][j]=false;
}
}
mark[1][1]=mark[n][m]=false;//
flag=dfs(1,1);//第二次dfs
if(flag)cout<<2<<endl;
else cout<<1<<endl;
}
return 0;
}
// /\ | / |**、
// / \ | / | \
// / \ |/ | / _____ ____ | /
// /------\ |\ |__/ / \ \ /\ / / \ | /
// / \ | \ | / \ \ / \ / /______\ |/
// / \ | \ | \ / \ / \ / \ |
// / \ | \ | \_____/ \/ \/ \_____ |
/**
* ┏┓ ┏┓
* ┏┛┗━━━━━━━┛┗━━━┓
* ┃ ┃
* ┃ ━ ┃
* ┃ > < ┃
* ┃ ┃
* ┃... ⌒ ... ┃
* ┃ ┃
* ┗━┓ ┏━┛
* ┃ ┃ Code is far away from bug with the animal protecting
* ┃ ┃ 神兽保佑,代码无bug
* ┃ ┃
* ┃ ┃
* ┃ ┃
* ┃ ┃
* ┃ ┗━━━┓
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━┳┓┏┛
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛
*/
// warm heart, wagging tail,and a smile just for you!
//
// _ooOoo_
// o8888888o
// 88" . "88
// (| -_- |)
// O\ = /O
// ____/`---'\____
// .' \| |// `.
// / \||| : |||// \
// / _||||| -:- |||||- \
// | | \\ - /// | |
// | \_| ''\---/'' | |
// \ .-\__ `-` ___/-. /
// ___`. .' /--.--\ `. . __
// ."" '< `.___\_<|>_/___.' >'"".
// | | : `- \`.;`\ _ /`;.`/ - ` : | |
// \ \ `-. \_ __\ /__ _/ .-` / /
// ======`-.____`-.___\_____/___.-`____.-'======
// `=---='
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//