POJ 1979 搜索 水题

原文链接: POJ 1979 搜索 水题

上一篇: POJ 3070 简单快速幂

下一篇: POJ 1980 DFS 剪枝

题意:给你一个row*col的矩阵,上面的'#'代表你不能走的地方,'.'表示你能走的地方, '@' 表示你的起点,问你最多能走多少格。

dfs

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

#define LL long long
int const MAX = 1e6 + 1;
int const INF = 1 << 30;
double const EPS = 0.00000001;
using namespace std;

int mp[20][20], n, m, ans = 0, dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};
char s[21];

void dfs(int x, int y){
    mp[x][y] = 0;
    for (int k = 0; k < 4; k++){
        int nx = x + dir[k][0], ny = y + dir[k][1];
        if (nx >= 0 && ny >= 0 && nx < n && ny < m && mp[nx][ny]){
            ans++;
            dfs(nx, ny);
        }
    }
}
int main(){
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);

    int x, y;
    while (scanf("%d%d", &m, &n), n + m){
        for (int i = 0; i < n; i++){
            scanf("%s", s);
            for (int j = 0; j < m; j++){
                mp[i][j] = (s[j] == '#' ? 0 : 1);
                if (s[j] == '@')
                    x = i, y = j;
            }
        }
        ans = 1;
        dfs(x, y);
        printf("%d\n", ans);
    }
    return 0;
}

bfs

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

#define LL long long
int const MAX = 1e6 + 1;
int const INF = 1 << 30;
double const EPS = 0.00000001;
using namespace std;

int mp[20][20], n, m, ans = 0, dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};
char s[21];

struct Node {
    int x, y;
};
int bfs(Node st){
    int cnt = 1;
    queue<Node> q;
    q.push(st);
    Node t;
    mp[st.x][st.y] = 0;
    while (!q.empty()){
        Node nd = q.front();
        q.pop();
        for (int k = 0; k < 4; k++){
            t.x = nd.x + dir[k][0], t.y = nd.y + dir[k][1];
            if (t.x >= 0 && t.y >= 0 && t.x < n && t.y < m && mp[t.x][t.y]){
                mp[t.x][t.y] = 0;
                q.push(t);
                cnt++;
            }
        }
    }
    return cnt;
}
int main(){
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);

    Node st;
    while (scanf("%d%d", &m, &n), n + m){
        for (int i = 0; i < n; i++){
            scanf("%s", s);
            for (int j = 0; j < m; j++){
                mp[i][j] = (s[j] == '#' ? 0 : 1);
                if (s[j] == '@')
                    st.x = i, st.y = j;
            }
        }
        printf("%d\n", bfs(st));
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值