题解:AT_abc378_d [ABC378D] Count Simple Paths
T4
洛谷传送门
AT传送门
题意
给定一个长
思路
如果使用 BFS 算法,暴力去做
但是因为可以上下左右走,只要不走重复和障碍即可,BFS 的话并不是很好去统计方案数。(也可能是我太菜了xwx)
注意到数据范围很小。可以使用 回溯算法 计算。
每次到一个点,先把这个点打上标记,然后查看周围四个点哪些点可以继续走。走到
回溯的时候把标记取消了即可。
设一个点的方案数为
不妨跑一下极限数据,即
代码
// Problem: D - Count Simple Paths
// Contest: AtCoder - AtCoder Beginner Contest 378
// URL: https://atcoder.jp/contests/abc378/tasks/abc378_d
// Memory Limit: 1024 MB
// Time Limit: 2000 ms
//
// Powered by CP Editor (https://cpeditor.org)
#include<bits/stdc++.h>
using namespace std;
const int MAXN=10+10;
const int mod1=1e9+7;
const int mod2=998244353;
const int inf_int=0x7f7f7f7f;
const long long inf_long=0x7f7f7f7f7f7f7f7f;
const double eps=1e-9;
char Buf[1<<23],*P1=Buf,*P2=Buf;
#define getchar() (P1==P2&&(P2=(P1=Buf)+fread(Buf,1,1<<23,stdin),P1==P2)?EOF:*P1++)
template<typename type>
inline void read(type &x){
x=0;
bool f=false;
char ch=getchar();
while(ch<'0'||ch>'9') f|=ch=='-',ch=getchar();
while(ch>='0'&&ch<='9') x=x*10+(ch^48),ch=getchar();
if(f) x=-x;
}
template<typename type,typename... args>
inline void read(type &x,args&... y){
read(x),read(y...);
}
int h,w,k,ans;
char g[MAXN][MAXN];
bool vis[MAXN][MAXN];
struct node{
int x,y,dis;
};
void dfs(int x,int y,int dis){
if(dis==k){
ans++;
return;
}
vis[x][y]=true;
if(x!=1&&!vis[x-1][y]&&g[x-1][y]=='.') dfs(x-1,y,dis+1);
if(x!=h&&!vis[x+1][y]&&g[x+1][y]=='.') dfs(x+1,y,dis+1);
if(y!=1&&!vis[x][y-1]&&g[x][y-1]=='.') dfs(x,y-1,dis+1);
if(y!=w&&!vis[x][y+1]&&g[x][y+1]=='.') dfs(x,y+1,dis+1);
vis[x][y]=false;
}
signed main(){
cin>>h>>w>>k;
for(int i=1;i<=h;i++) for(int j=1;j<=w;j++) cin>>g[i][j];
for(int i=1;i<=h;i++){
for(int j=1;j<=w;j++){
if(g[i][j]=='#') continue;
dfs(i,j,0);
}
}
cout<<ans;
return 0;
}