POJ 1979 Red and Black (BFS)


**链接 : ** Here!

**思路 : ** 简单的搜索, 直接广搜就ok了.


/*************************************************************************
	> File Name: E.cpp
	> Author: 
	> Mail: 
	> Created Time: 2017年11月26日 星期日 10时51分05秒
 ************************************************************************/

#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <queue>
using namespace std;

#define MAX_N 30
int N, M, total_num;
int dx[4] = {0, 0, -1, 1};
int dy[4] = {-1, 1, 0, 0};
int vis[MAX_N][MAX_N];
char G[MAX_N][MAX_N];

struct Point {
    Point() {}
    Point(int x, int y) : x(x), y(y) {}
    int x, y;
};
Point st;

bool check(Point pt) {
    if (pt.x < 0 || pt.x >= N || pt.y < 0 || pt.y >= M) return false;
    if (vis[pt.x][pt.y]) return false;
    if (G[pt.x][pt.y] == '#') return false;
    return true;
}
void DFS(Point pt) {
    ++total_num;
    vis[pt.x][pt.y] = 1;
    for (int i = 0 ; i < 4 ; ++i) {
        Point temp(pt.x + dx[i], pt.y + dy[i]);
        if(!check(temp)) continue;
        vis[temp.x][temp.y] = 1;
        DFS(temp);
    }
}

void solve() {
    memset(vis, 0, sizeof(vis));
    for (int i = 0 ; i < N ; ++i) {
        for (int j = 0 ; j < M ; ++j) {
            if (G[i][j] == '@') {
                st.x = i; st.y = j;
                break;
            }
        }
    }
    DFS(st);
    printf("%d\n", total_num);
}
void read() {
    for (int i = 0 ; i < N ; ++i) {
        getchar();
        scanf("%s", G[i]);    
    }
}
int main() {
    // freopen("./in.in", "r", stdin);
    while (scanf("%d%d", &M, &N) != EOF) {
        if (N == 0 && M == 0) break;
        memset(G, 0, sizeof(G));
        total_num = 0;
        read();
        solve();
    }
    return 0;
}
posted @ 2017-11-27 11:32  ojnQ  阅读(149)  评论(0编辑  收藏  举报