题目地址(130. 被围绕的区域)
Posted 潜行前行
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了题目地址(130. 被围绕的区域)相关的知识,希望对你有一定的参考价值。
题目地址(130. 被围绕的区域)
https://leetcode.cn/problems/surrounded-regions/
题目描述
给你一个 m x n 的矩阵 board ,由若干字符 'X' 和 'O' ,找到所有被 'X' 围绕的区域,并将这些区域里所有的 '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"]]
解释:被围绕的区间不会存在于边界上,换句话说,任何边界上的 'O' 都不会被填充为 'X'。 任何不在边界上,或不与边界上的 'O' 相连的 'O' 最终都会被填充为 'X'。如果两个元素在水平或垂直方向相邻,则称它们是“相连”的。
示例 2:
输入:board = [["X"]]
输出:[["X"]]
提示:
m == board.length
n == board[i].length
1 <= m, n <= 200
board[i][j] 为 'X' 或 'O'
关键点
- 记忆搜索
代码
- 语言支持:Java
Java Code:
class Solution
int[][] dir = new int[][]1,0,-1,0,0,1,0,-1;
public void solve(char[][] board)
for(int i = 0; i < board.length;i++ )
for(int j = 0; j < board[0].length;j++ )
// 从边缘开始遍历
if( i ==0 || j == 0 || i == (board.length-1) || j == (board[0].length-1) )
if(board[i][j] == 'O')
dfs(i,j,board);
for(int i = 0; i < board.length;i++ )
for(int j = 0; j < board[0].length;j++ )
if(board[i][j] == 'O')
board[i][j] = 'X';
else if(board[i][j] == '1')
board[i][j] = 'O';
void dfs(int i,int j,char[][] board)
if( i < 0 || j < 0 || i > (board.length-1) || j > (board[0].length-1) || board[i][j] == 'X' || board[i][j] == '1' )
return;
board[i][j] = '1';
for(int[] epoch : dir)
dfs(i+epoch[0],j+epoch[1],board);
复杂度分析
令 n 为数组长度。
- 时间复杂度: O ( n ) O(n) O(n)
- 空间复杂度: O ( n ) O(n) O(n)
以上是关于题目地址(130. 被围绕的区域)的主要内容,如果未能解决你的问题,请参考以下文章