码迷,mamicode.com
首页 > 其他好文 > 详细

hdu1312

时间:2014-12-07 20:18:22      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:style   io   ar   color   os   sp   for   strong   on   

//简单搜索,只要走遍所有可达的路径

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

标签:style   io   ar   color   os   sp   for   strong   on   

原文地址:http://www.cnblogs.com/usedrosee/p/4149703.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!