给你一个 m x n
的矩阵 board
,由若干字符 'X'
和 'O'
组成,捕获 所有 被围绕的区域:
- 连接:一个单元格与水平或垂直方向上相邻的单元格连接。
- 区域:连接所有
'O'
的单元格来形成一个区域。 - 围绕:如果您可以用
'X'
单元格 连接这个区域,并且区域中没有任何单元格位于board
边缘,则该区域被'X'
单元格围绕。
通过将输入矩阵 board
中的所有 'O'
替换为 'X'
来 捕获被围绕的区域。
示例 1:
输入:board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
输出:[["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]
解释:
在上图中,底部的区域没有被捕获,因为它在 board 的边缘并且不能被围绕。
示例 2:
输入:board = [["X"]]
输出:[["X"]]
提示:
m == board.length
n == board[i].length
1 <= m, n <= 200
board[i][j]
为'X'
或'O'
深度优先遍历,注意分析题意,其他的就不多说了,上代码,看不懂的请留言或者私信,收到第一时间解答
class Solution {/**这个题的突破口是什么样的才能不被捕获:我理解如果不被捕获,这个格子必定连着某个边缘的格子因为边缘的格子能连通它,所以它才不被捕获,这样我们就从边缘的O开始感染,所有被感染到的标记一个Y这样最后除了Y之外的全部设置成X就可以了 */public void solve(char[][] board) {for(int i = 0; i < board.length; i++) {/**只有边缘才配感染 */if(board[i][0] == 'O') {infect(board, i, 0);}if(board[i][board[i].length - 1] == 'O') {infect(board, i, board[i].length - 1);}}for(int j = 0; j < board[0].length; j++) {/**只有边缘才配感染 */if(board[0][j] == 'O') {infect(board, 0, j);}if(board[board.length - 1][j] == 'O') {infect(board, board.length - 1, j);}}/**根据感染的结果进行赋值*/for(int i = 0; i < board.length; i++) {for(int j = 0; j < board[i].length; j++) {board[i][j] = board[i][j] == 'Y'? 'O' : 'X';}}}public void infect(char[][] board, int row, int col) {if(row < 0 || row >= board.length || col < 0 || col >= board[row].length || board[row][col] != 'O') {return;}/**把自己感染成'Y'*/board[row][col] = 'Y';/**感染自己的上下左右 */infect(board, row - 1, col);infect(board, row, col + 1);infect(board, row + 1, col);infect(board, row, col - 1);}
}