当前位置:网站首页>Leetcode search questions

Leetcode search questions

2022-06-11 01:38:00 Black white grey 12345

Catalog

 

130. The surrounding area


130. The surrounding area

  Convert to inverse problem , Starting from the boundary, the depth traversal first marks the non-conforming positions

class Solution {
public:
    vector<int> directions {-1, 0, 1, 0, -1};
    void dfs(vector<vector<char>>& board, int r, int c) {
        board[r][c] = 'A';//  use 'A' Mark the unqualified 'O' spot 
        for (int k = 0; k < 4; ++k) {
            int x = r + directions[k], y = c + directions[k+1];
            if (x >= 0 && x < board.size() && y >=0 && y < board[0].size() && board[x][y] == 'O') {
                dfs(board, x, y);
            }
        }
    }
    void solve(vector<vector<char>>& board) {
        int m = board.size(), n = board[0].size();
		//  Traverse two longitudinal boundaries 
        for (int i = 0; i < m; ++i) {
            if (board[i][0] == 'O'){
                dfs(board, i, 0);
            }
            if (board[i][n-1] == 'O'){
                dfs(board, i, n-1);
            }
        }
		//  Traverse two horizontal boundaries 
        for (int j = 0; j < n; ++j) {
            if (board[0][j] == 'O') {
                dfs(board, 0, j);
            }
            if (board[m-1][j] == 'O') {
                dfs(board, m-1, j);
            }
        }
		//  According to the traversal of the tag information will meet the conditions 'O' Replace with 'X'
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (board[i][j] == 'O') {
                    board[i][j] = 'X';
                }else if (board[i][j] == 'A') {
                    board[i][j] = 'O'; //  Restore the unqualified 
                }
            }
        }
    }
};

原网站

版权声明
本文为[Black white grey 12345]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203020624063857.html