• poj 1979 走多少个‘ . '问题 dfs算法


    题意:给你一个迷宫地图,让你走。问最多可以走多少个“."

    思路:dfs

    1. 找到起点,然后对起点进行dfs操作。
    2. dfs操作时,要把当前的位置标志成"#"表示已经走过,然后进行四个方向的遍历。如果当前可以满足不超过范围,且是"."的就继续dfs

    代码上的注意:四个方向上的遍历,用一个二维数组比较方便

    const int dir[4][2]
    {
        { 0,-1 },{ 1,0 },{ 0,1 },{ -1,0 }
    };

    解决问题的代码:

    #include <iostream>
    #include <cstdio>
    using namespace std;
    int w, h;
    int ans = 0;
    char map[21][21];
    const int dir[4][2]
    {
        { 0,-1 },{ 1,0 },{ 0,1 },{ -1,0 }
    };
    int bfs(const int x, const int y)
    {
        map[x][y] = '#';
        ++ans;
        for (int i = 0; i < 4; i++)
        {
            int cur_x = x + dir[i][0];
            int cur_y = y + dir[i][1];
            if (cur_x >= 0 && cur_x < h&&cur_y >= 0 && cur_y < w&&map[cur_x][cur_y] == '.')
                bfs(cur_x, cur_y);
        }
        return ans;
    }
    int main()
    {
        while (scanf("%d%d", &w, &h) != EOF)
        {
            if (w == 0 && h == 0) break;
            for (int i = 0; i < h; i++)
                for (int j = 0; j < w; j++)
                    cin >> map[i][j];
            bool flag = true;
            if (flag)
            {
                for (int i = 0; i<h; i++)
                    for (int j = 0; j<w; j++)
                        if (map[i][j] == '@')
                        {
                            cout << bfs(i, j) << endl;
                            flag = false;
                        }
            }
            if (!flag)
            {
                ans = 0;
                continue;
            }
        }
    }
    君子知命不惧,自当日日自新
  • 相关阅读:
    笔记-归并排序
    Repeated Substring Pattern
    Assign Cookies
    Number of Boomerangs
    Paint Fence
    Path Sum III
    Valid Word Square
    Sum of Two Integers
    Find All Numbers Disappeared in an Array
    First Unique Character in a String
  • 原文地址:https://www.cnblogs.com/xuxiaojin/p/9405474.html
Copyright © 2020-2023  润新知