您的位置:首页 > 其它

【转载】【leetcode】Surrounded regions

2013-09-18 17:34 211 查看


Surrounded regions

题意:假设一个二维图由X和O组成,将所有被X围住的O转换成X

如:XXXX
XOOX
XXOX
XOXX

变成:XXXX
XXXX
XXXX
XOXX

思路:从O处开始BFS,用一个队列记录遍历的路径,如果这条路径都是在边界以内,没有超出边界,则将路径上所有的O变成X
代码:
void solve(vector<vector<char>> &board) {
// Start typing your C/C++ solution below        // DO NOT write int main() function                int N = board.size();        if (N == 0) return;        int M = board[0].size();        if (M == 0) return;        vector<vector<bool> > mark(N, vector<bool>(M, false));                int dx[4] = {-1, 1, 0, 0};//上下左右四个方向        int dy[4] = {0, 0, -1, 1};                for (int i = 0; i < N; i++)            for (int j = 0; j < M; j++)            {                if (!mark[i][j] && board[i][j] == 'O')                {                    vector<int> queX, queY;//遍历路径                    queX.push_back(i);                    queY.push_back(j);                    mark[i][j] = true;                    int head = 0;                    bool result = !(i == 0 || j == 0 || i == N - 1 || j == M - 1) ;//是否在边界以内                                        while (head < queX.size())                    {                        int nx = queX[head];                        int ny = queY[head];                        head++;                        for (int i = 0; i < 4; i++)                        {                            int nextX = nx + dx[i];                            int nextY = ny + dy[i];                            if (nextX >= 0 && nextX < N && nextY >= 0 && nextY < M)                            {                                if (!mark[nextX][nextY] && board[nextX][nextY] == 'O')                                {                                    mark[nextX][nextY] = true;                                    queX.push_back(nextX);                                    queY.push_back(nextY);                                    if (nextX == 0 || nextY == 0 || nextX == N - 1 || nextY == M - 1) //遍历到了边界                                        result = false;                                }                            }                        }                    }                    if (result)                    {                        for (int i = 0; i < queX.size(); i++)                            board[queX[i]][queY[i]] = 'X';                    }                }            }    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: