DFS/BFS
2527. Fj & haozi
题意:haozi 很淘气,最近 FJ 带了很多好吃的,haozi 乘 FJ 不在的时候偷吃了很多好吃的,FJ 回来发现了,决定一定要抓住 haozi。
但是 haozi 很聪明,假设原来他在 16 号楼,那么下一分钟必定是在 15 号楼或者 17 号楼。
如果他一开始在 1 号楼,那么下一分钟只能在 2 号楼。
如果他一开始在 n 号楼,那么下一分钟一定在 n−1 号楼。
现在一共有 n 号楼(编号为1, 2, …, n),一开始 haozi 在 p 号楼,求过了 m 分钟,haozi 出现在 t 号楼的一共有多少种行走方案数。
输入格式
第一行有一个整数cas(0<cas⩽100),表示测试数据数。接下来 cas 行,每行有四个整数:n,p,m,t(0<n,p,t<100, 0<m<20) ,每个整数表示的含义见题面。
输出格式
每组测试数据一行,每行输出一个整数,表示总共的行走方案数。
#include<bits/stdc++.h> using namespace std; int sum=0; int n,p,m,t; void dfs(int a,int cnt){ if(a==t&&cnt==m){ sum++; return ; } if(cnt>m) return; if(a==1){ dfs(a+1,cnt+1); }else if(a==n){ dfs(a-1,cnt+1); }else{ dfs(a+1,cnt+1); dfs(a-1,cnt+1); } } int main(){ int cas; cin>>cas; while(cas--){ sum=0; cin>>n>>p>>m>>t; dfs(p,0); cout<<sum<<endl; } return 0; } //p->t m
2848. 华师大卫星照片(DFS判断最大连通块)
#include<iostream> #include<algorithm> #include<cstring> #include<string> using namespace std; int w,h; char s[1010][85]; int m[4][2]={{-1,0},{1,0},{0,-1},{0,1}}; int f[1010][85]; int maxx=0; void dfs(int& sum,int r,int c){ int tr,tc; if(r<0||r>=h||c<0||c>=w){ return; } if(s[r][c]=='*'&&!f[r][c]){ f[r][c]=1; sum++; for(int i=0;i<4;i++){ tr=r+m[i][0]; tc=c+m[i][1]; dfs(sum,tr,tc); } } } int main(){ cin>>w>>h; for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ cin>>s[i][j]; } } for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ if(s[i][j]=='*'&&!f[i][j]){ int sum=0; dfs(sum,i,j); maxx=max(sum,maxx); } } } cout<<maxx<<endl; } //*建筑区

浙公网安备 33010602011771号