zoukankan      html  css  js  c++  java
  • 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;
    }


  • 相关阅读:
    android 添加图片时错误:android libpng error: Not a PNG file
    hdu4553
    zoj2706
    zoj3349
    zoj3606
    主席树 静态区间第k大
    主席树:动态 Kth
    zoj3633
    zoj3381
    zoj 3540
  • 原文地址:https://www.cnblogs.com/usedrosee/p/4149703.html
Copyright © 2011-2022 走看看