POJ - 1979 Red and Black

bfs / dfs 都可以做目前最熟的就是bfs了,所以用bfs做的
期间遇到了不是问题的问题,搁置了老长时间,快气哭了。

因为某种思维定式耽误了老长老长时间,已经有两个题这样了, 为了以后避免这种情况有必要单独拉出来说一说(严肃脸)

对于这道题的这两种样例

11 6
..#..#..#..
..#..#..#..
..#..#..###
..#..#..#@.
..#..#..#..
..#..#..#..


7 7
..#.#..
..#.#..
###.###
...@...
###.###
..#.#..
..#.#..

这两个样例第二个对,第一个错,我怎么也没想明白怎么回事,程序反反复复看了好多遍也找不到错误在哪,然后…老长老长时间(大约一个半小时…一直看这个题),就去搜索题解了,然后发现和我写的一样啊!然后一行一行对比,才发现第一个数字代表的是列,第二个是行!
艹,我还是如此弱智,然后修改两个变量输入的位置就ac了。

做的题多了,很容易有这样的思维定式,真的是这样,比如这个是行在前,列在后。
还有KMP的时候子串优先输入,主串后输入…因为输入位置的原因耽误老长时间真是太亏了,希望记住这个教训

以后dfs学的熟悉了,在用dfs做一遍(待更新)

bfs

#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
char map[22][22];
bool vis[22][22];
int d[4][2] = {{1,0},{-1,0},{0,-1},{0,1}};
int nl,ml;
struct node{
    int x, y;
}s,n,t;
queue<node> q;
int bfs(){
    memset(vis, false, sizeof(vis));
    int cnt = 1;
    vis[s.x][s.y] = true;
    while(!q.empty()) q.pop();
    q.push(s);
    while(!q.empty()){
        n = q.front();
        q.pop();
        for(int i = 0; i < 4; ++i){
            t.x = n.x + d[i][0];
            t.y = n.y + d[i][1];
            if(t.x >= 0 && t.x < nl && t.y >= 0 && t.y < ml && map[t.x][t.y] == '.' && !vis[t.x][t.y]){
                cnt++;
                vis[t.x][t.y] = true;
                q.push(t);
            }
        }
    }
    return cnt;
}
int main(){
    while(cin >> ml >> nl){
        if(!nl&&!ml) break;
        memset(map, 0, sizeof(map));
        for(int i = 0; i < nl; ++i)
            for(int j = 0; j < ml; ++j){
                cin >> map[i][j];
                if(map[i][j] == '@'){s.x = i; s.y = j;}
            }
        int ans  = bfs();
        cout << ans << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44031744/article/details/88025031