题意:
解题思路:
思路:O(n×m),其中 n 和 m 分别为矩阵的行数和列数。
1. 从边界出发,对图递归dfs搜索,如果找到O, 则替换成#号作为占位符;
2. 递归结束后,将剩下的O(除边界外的)替换成X,将第一步替换的#号还原成O;
PHP代码实现:
class Solution {
private $row,$col;
/**
* @param String[][] $board
* @return NULL
*/
function solve(&$board) {
if (empty($board)) return;
$this->row = count($board);
$this->col = count($board[0]);
for ($i = 0; $i < $this->row; $i++) {
for ($j = 0; $j < $this->col; $j++) {
$isEdge = $i == 0 || $j == 0 || $i == $this->row - 1 || $j == $this->col - 1;
if ($isEdge && $board[$i][$j] == 'O') $this->dfs($board, $i, $j);
}
}
for ($i = 0; $i < $this->row; $i++) {
for ($j = 0; $j < $this->col; $j++) {
if ($board[$i][$j] == 'O') $board[$i][$j] = 'X';
if ($board[$i][$j] == '#') $board[$i][$j] = 'O';
}
}
return;
}
function dfs(&$board, $i, $j) {
if ($i < 0 || $j < 0 || $i >= $this->row
|| $j >= $this->col || $board[$i][$j] == 'X' || $board[$i][$j] == '#') {
return;
}
$board[$i][$j] = '#';
$this->dfs($board, $i - 1, $j);
$this->dfs($board, $i + 1, $j);
$this->dfs($board, $i, $j - 1);
$this->dfs($board, $i, $j + 1);
}
}
GO代码实现:
func solve(board [][]byte) {
if board == nil || len(board) == 0 {
return
}
for i := 0; i < len(board); i++ {
for j := 0; j < len(board[0]); j++ {
isEdge := i == 0 || j == 0 || i == len(board) - 1 || j == len(board[0]) - 1
if isEdge && board[i][j] == 'O' {
dfs(board, i, j)
}
}
}
for i := 0; i < len(board); i++ {
for j := 0; j < len(board[0]); j++ {
if board[i][j] == 'O' {
board[i][j] = 'X'
}
if board[i][j] == '#' {
board[i][j] = 'O'
}
}
}
}
func dfs(board [][]byte, i, j int) {
if i < 0 || j < 0 || i >= len(board) ||
j >= len(board[0]) || board[i][j] == 'X' || board[i][j] == '#' {
return
}
board[i][j] = '#'
dfs(board, i - 1, j)
dfs(board, i + 1, j)
dfs(board, i, j - 1)
dfs(board, i, j + 1)
}