本文主要是介绍130. 被围绕的区域——DFS,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
class Solution {
public:int rows, columns;void solve(vector<vector<char>>& board) {rows = board.size();columns = board[0].size();for(auto i = 0; i < rows; ++i){dfs(board, i, 0); //左边界dfs(board, i, columns - 1); //右边界}for(auto j = 0; j < columns; ++j){dfs(board, 0, j); //上边界dfs(board, rows - 1, j); //下边界}for(auto i = 0; i < rows; ++i){for(auto j = 0; j < columns; ++j){if(board[i][j] == 'A')board[i][j] = 'O';else if(board[i][j] == 'O')board[i][j] = 'X';}}}void dfs(vector<vector<char>>& board, int row, int column){//如果超过边界或者不是‘O’//只有包含边界上的O的区域才会被保留,先把存在边界上的O的所有区域改为A//那么剩下的O就是包裹在内部的,也就是要改为X的if(row < 0 || row >= rows || column < 0 || column >= columns || board[row][column] != 'O'){return;}board[row][column] = 'A'; //和边界上的O接触过的都先换成Adfs(board, row - 1, column); //上dfs(board, row, column - 1); //左dfs(board, row + 1, column); //下dfs(board, row, column + 1); //右}
};
Accepted
58/58 cases passed (12 ms)
Your runtime beats 69.35 % of cpp submissions
Your memory usage beats 58.44 % of cpp submissions (9.8 MB)
这篇关于130. 被围绕的区域——DFS的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!