洛谷P1451 求细胞数量
题目链接:https://www.luogu.com.cn/problem/P1451
开始的时候想麻烦了,经过一次次的调不过终于成功了;
本题其实是一道很中规中矩的搜索题,但是一些细节方面需要注意,并且值得注意的是,标记数组vis是不用回溯的,因为一部分元素||字符只能算一次,所以说就免去回溯了;
代码及其思路如下:(dfs)
1 #include<bits/stdc++.h> 2 using namespace std; 3 int n,m; 4 bool vis[110][110]; 5 char ch[110][110]; 6 int ans; 7 int dir[4][2]={ 8 {-1,0}, 9 {0,-1}, 10 {1,0}, 11 {0,1} 12 }; 13 void dfs(int x,int y) 14 { 15 vis[x][y]=true;//走过的元素标记 16 for(register int i=0;i<4;i++) 17 { 18 int newx=x+dir[i][0]; 19 int newy=y+dir[i][1]; 20 if(newx<=0||newx>n||newy<=0||newy>m||vis[newx][newy]||ch[newx][newy]=='0')//如果下一个元素不满足条件就跳过 21 continue; 22 dfs(newx,newy);//vis不必回溯因为一部分元素算一次就可以了 23 } 24 } 25 int main() 26 { 27 ios::sync_with_stdio(false); 28 cin>>n>>m; 29 for(register int i=1;i<=n;i++) 30 { 31 for(register int j=1;j<=m;j++) 32 { 33 cin>>ch[i][j]; 34 } 35 } 36 for(register int i=1;i<=n;i++) 37 { 38 for(register int j=1;j<=m;j++) 39 { 40 if(ch[i][j]!='0'&&!vis[i][j])//注意是字符串并且要走没走过的 41 { 42 dfs(i,j); 43 ans++; 44 } 45 } 46 } 47 cout<<ans<<endl; 48 return 0; 49 }
下面提供bfs思路:
1 #include<bits/stdc++.h> 2 using namespace std; 3 struct node 4 { 5 int x,y; 6 }; 7 int n,m,ans=0;//n行m列,ans为答案 8 int a[105][105];//存矩阵 9 bool used[105][105];//记录是否走过 10 int dx[4]={-1,1,0,0};//向上下左右走一步行号和列好的改变 11 int dy[4]={0,0,-1,1}; 12 void bfs(int x,int y)//bfs 13 { 14 queue<node>q; 15 used[x][y]=true; 16 node st,nxt; 17 st.x=x; 18 st.y=y; 19 q.push(st); 20 while(!q.empty()) 21 { 22 st=q.front(); 23 q.pop(); 24 for(int i=0;i<4;i++) 25 { 26 nxt.x=st.x+dx[i]; 27 nxt.y=st.y+dy[i]; 28 if(a[nxt.x][nxt.y]==0 || used[nxt.x][nxt.y]==true) 29 continue; 30 used[nxt.x][nxt.y]=true;//把这一连通块的点染色 31 q.push(nxt); 32 } 33 34 } 35 } 36 int main() 37 { 38 cin>>n>>m; 39 memset(a,0,sizeof(a)); 40 for(int i=1;i<=n;i++) 41 for(int j=1;j<=m;j++) 42 scanf("%1d",&a[i][j]); 43 for(int i=1;i<=n;i++) 44 { 45 for(int j=1;j<=m;j++) 46 { 47 if(!used[i][j]&&a[i][j]!=0) 48 { 49 bfs(i,j); 50 ans++;//若这一连通块没搜过ans++ 51 } 52 } 53 } 54 cout<<ans; 55 return 0; 56 }
本文来自博客园,作者:江上舟摇,转载请注明原文链接:https://www.cnblogs.com/LQS-blog/p/16025831.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构