首页 > 代码库 > hdu1312
hdu1312
//简单搜索,只要走遍所有可达的路径
BFS版:
#include "iostream"#include "cstdio"#include "memory.h"#include "queue"using namespace std;const int MAX = 22;const int dx[] = {1,-1,0,0},dy[] = {0,0,1,-1};char map[MAX][MAX];int vis[MAX][MAX];int x,y;int n,m;pair<int ,int> now;int bfs(){ int cnt = 1; memset(vis,0,sizeof(vis)); queue< pair<int,int> > que; que.push(make_pair(x,y)); vis[x][y] = 1; while (!que.empty()) { now = que.front(); que.pop(); int i,tx,ty; for (i = 0;i < 4; ++ i) { tx = now.first + dx[i]; ty = now.second + dy[i]; if (tx < 0 || ty < 0|| tx >= m || ty >= n) continue; if (vis[tx][ty]) continue; if (map[tx][ty] == ‘.‘) { cnt++; que.push(make_pair(tx,ty)); } vis[tx][ty] = 1; } } return cnt;}int main(){ int i,j; while (cin >> n >> m,m+n) { //m行 n列 for (i = 0; i < m; ++ i) for (j = 0;j < n ; ++ j) { cin >> map[i][j]; if (map[i][j] == ‘@‘) x = i,y = j; } //cout << x << " " << y << endl; cout << bfs() << endl; } return 0;}
DFS:
#include "iostream"#include "cstdio"#include "memory.h"#include "queue"using namespace std;const int MAX = 22;const int dx[] = {1,-1,0,0},dy[] = {0,0,1,-1};char map[MAX][MAX];int vis[MAX][MAX];int x,y;int n,m;int cnt;void dfs(int x,int y){ vis[x][y] = 1; int i, tx, ty; for (i = 0;i < 4 ; ++i) { tx = x + dx[i]; ty = y + dy[i]; if (tx >= 0 && ty >= 0 && tx < m && ty < n && map[tx][ty] != ‘#‘ && !vis[tx][ty]) { cnt ++; dfs(tx,ty); } }}int main(){ int i,j; while (cin >> n >> m,m+n) { //m行 n列 for (i = 0; i < m; ++ i) for (j = 0;j < n ; ++ j) { cin >> map[i][j]; if (map[i][j] == ‘@‘) x = i,y = j; } cnt = 1; dfs(x,y); cout << cnt << endl; memset(vis,0,sizeof(vis)); } return 0;}
hdu1312
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。