Hrbust 1143 (bfs)
来源:互联网 发布:淘宝网购买流程 编辑:程序博客网 时间:2024/06/03 19:12
题意:
给出n*m的矩形地图,从一个原点出发找出小于等于原点的个数。
思路:
其实可以用深搜去写这道题,不过可以练习一下bfs的写题思路,注意点就是原点
的判断(check)和细节,比如我经常把s,t写错。
#include <iostream>#include <cstdio>#include <cstring>#include <queue>using namespace std;const int MAXN = 1005;struct P{ int x,y;};int n,m,s,t;int map[MAXN][MAXN];bool vis[MAXN][MAXN];int dir[4][2] = {0,-1,0,1,1,0,-1,0};int check(P a){ if(a.x >= 0 && a.x < n && a.y >= 0 && a.y < m && vis[a.x][a.y] != 1 && map[a.x][a.y] <= map[s-1][t-1]) return true; else return false;}int solve(){ memset(vis,0,sizeof(vis)); queue<P>que; P now,temp; now.x = s-1; now.y = t-1; que.push(now); vis[s-1][t-1] = true; int ans = 1; while(!que.empty()) { temp = que.front(); que.pop(); //vis[tmep.x][temp.y] = true; for(int i = 0;i < 4; i++) { now.x = temp.x + dir[i][0]; now.y = temp.y + dir[i][1]; if(check(now)) { que.push(now); ans++; vis[now.x][now.y] = true; } } } return ans;}int main(){ //freopen("in.txt","r",stdin); while(scanf("%d%d%d%d",&n,&m,&s,&t) != EOF) { for(int i = 0;i < n; i++) { for(int j = 0;j < m; j++) { scanf("%d",&map[i][j]); } } int ans = solve(); printf("%d\n",ans); } return 0;}
bfs写法,注意:dfs的入口和出口
#include <iostream>#include <cstdio>#include <cstring>using namespace std;const int MAXN = 1005;int ans;int n,m,s,t;int map[MAXN][MAXN];int vis[MAXN][MAXN];int dir[4][2] ={0,1,0,-1,1,0,-1,0};void dfs(int a,int b){ ans++,vis[a][b] = true; for(int i = 0;i < 4; i++) { int x = a + dir[i][0]; int y = b + dir[i][1]; if(x >= 1 && x <= n && y >= 1 && y <= m && vis[x][y] == false && map[x][y] <= map[s][t]) dfs(x,y); }}int main(){ //freopen("in.txt","r",stdin); while(scanf("%d%d%d%d",&n,&m,&s,&t) != EOF) { for(int i = 1;i <= n; i++) { for(int j = 1;j <= m;j ++) scanf("%d",&map[i][j]); } ans = 0; memset(vis,0,sizeof(vis)); dfs(s,t); printf("%d\n",ans); } return 0;}
0 0
- Hrbust 1143 (bfs)
- bfs\dfs hrbust 1143
- hrbust 2159【BFS水题】
- bfs hrbust 2188
- bfs hrbust 2074
- bfs hrbust 1948
- hrbust 院赛 bfs 骑士相遇
- HRBUST 1012 Catch That Cow (BFS)
- bfs 思路 hrbust院赛初赛D
- hrbust/哈理工oj 1617 回家【BFS+BFS】
- hrbust 1143 泉水
- hrbust 1143 泉水
- hrbust 1143泉水DFS
- HRBUST
- HRBUST
- HRBUST
- HRBUST
- HRBUST
- ubuntu+eclipse测试opengl(glut和glfw)
- java程序 记事本
- C:单链表的简单实现
- chapter6——输入n个字符串,按由小到大顺序输出
- 全排列
- Hrbust 1143 (bfs)
- 状态模式
- FreeMarker 指令
- webview的使用
- 在maven中添加依赖,把自己写的插件
- linux基础入门学习
- 核密度估计(KDE)
- 100T核心数据库升级历险记
- LeetCode 524. Longest Word in Dictionary through Deleting