HDU - 1241 Oil Deposits (簡單搜索)

題意:*代表土,@代表油,問一共有幾塊油田,8個方向連接就算是一塊

思路:8個方向搜索,每次搜索記錄個數,搜索裏面記得標記,更改地圖;

#include<iostream>
#include<algorithm>
#include<queue>
#include<cstring>

using namespace std;

const int maxn = 1000;
int n, m;
char mp[maxn][maxn];
int book[maxn][maxn];
int to[8][2] = {-1,0, 1,0, 0,1, 0,-1, -1,-1, 1,1, -1,1, 1,-1};

bool check(int x, int y) {
    if(x < 1 || y < 1 || x > n || y > m) return false;
    if(mp[x][y] == '@' && !book[x][y]) return true;
    return false;
}

void bfs(int x, int y) {
    for(int i = 0; i < 8; i++) {
        int nx = x + to[i][0];
        int ny = y + to[i][1];
        if(!check(nx,ny)) continue;
        book[nx][ny] = 1;
        mp[nx][ny] = '*';
        bfs(nx, ny);
    }
}
int main() {
    while(cin >> n >> m && n && m) {
        memset(book, 0, sizeof(book));
        for(int i = 1; i <= n; i++) {
            for(int j = 1; j <= m ;j++) {
                cin >> mp[i][j];
            }
        }
        int ans = 0;
        for(int i = 1; i <= n; i++) {
            for(int j = 1; j <= m ;j++) {
                if(mp[i][j] == '@') {
//                  cout << i << " " << j << endl;
                    book[i][j] = 1;
                    bfs(i, j);
                    ans ++;
                }
            }
        }
        cout << ans << endl;
    } 
    return 0;
} 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章