b_lc_黑白翻转棋(一个方向枚举到底 + bfs)

给一个有旗子的棋盘,下一步可放置一枚黑棋,请问选手这一步最多能翻转多少枚白棋。

思路:一路枚举到底,控制好条件即可

class Solution {
public:
    int n, m;
    struct node {
        int x, y;
    };
    const int d[8][2] = {  {-1, 0}, {1, 0},  {0, -1}, {0, 1},  {-1, -1},{-1, 1},  {1, -1}, {1, 1}};
    int bfs(int x, int y, const vector<string>& g) {
        queue<node> q;
        q.push({x, y});
        vector<string> next = g;
        next[x][y] = 'X';
        int ans = 0;

        while (!q.empty()) {
            node t = q.front();
            q.pop();
            //一个方向枚举到底,直到遇到一个黑棋
            for (int i = 0; i < 8; ++i) {
                int sx = t.x, sy = t.y;
                int tx = sx + d[i][0], ty = sy + d[i][1];
                while (tx >= 0 && tx < n && ty >= 0 && ty < m && next[tx][ty] == 'O') {
                    tx += d[i][0], ty += d[i][1];
                }
                //遇到了白棋,然后遇到黑棋结束
                if (tx >= 0 && tx < n && ty >= 0 && ty < m && next[tx][ty] == 'X') {
                    sx += d[i][0], sy += d[i][1];
                    while (sx != tx || sy != ty) {
                        ans++;
                        q.push({sx, sy});
                        next[sx][sy] = 'X';
                        sx += d[i][0], sy += d[i][1];
                    }
                }
            }
        }
        return ans;
    }
    int flipChess(vector<string>& g) {
        n = g.size(), m = g[0].size();
        int ans = 0;

        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m; ++j) {
                if (g[i][j] == '.') {
                    ans = max(ans, bfs(i, j, g));
                }
            }
        }
        return ans;
    }
};
posted @ 2021-09-11 22:06  童年の波鞋  阅读(155)  评论(0编辑  收藏  举报