题意:

image.png

解题思路:

  1. 思路:O(n×m),其中 n m 分别为矩阵的行数和列数。
  2. 1. 从边界出发,对图递归dfs搜索,如果找到O, 则替换成#号作为占位符;
  3. 2. 递归结束后,将剩下的O(除边界外的)替换成X,将第一步替换的#号还原成O

PHP代码实现:

  1. class Solution {
  2. private $row,$col;
  3. /**
  4. * @param String[][] $board
  5. * @return NULL
  6. */
  7. function solve(&$board) {
  8. if (empty($board)) return;
  9. $this->row = count($board);
  10. $this->col = count($board[0]);
  11. for ($i = 0; $i < $this->row; $i++) {
  12. for ($j = 0; $j < $this->col; $j++) {
  13. $isEdge = $i == 0 || $j == 0 || $i == $this->row - 1 || $j == $this->col - 1;
  14. if ($isEdge && $board[$i][$j] == 'O') $this->dfs($board, $i, $j);
  15. }
  16. }
  17. for ($i = 0; $i < $this->row; $i++) {
  18. for ($j = 0; $j < $this->col; $j++) {
  19. if ($board[$i][$j] == 'O') $board[$i][$j] = 'X';
  20. if ($board[$i][$j] == '#') $board[$i][$j] = 'O';
  21. }
  22. }
  23. return;
  24. }
  25. function dfs(&$board, $i, $j) {
  26. if ($i < 0 || $j < 0 || $i >= $this->row
  27. || $j >= $this->col || $board[$i][$j] == 'X' || $board[$i][$j] == '#') {
  28. return;
  29. }
  30. $board[$i][$j] = '#';
  31. $this->dfs($board, $i - 1, $j);
  32. $this->dfs($board, $i + 1, $j);
  33. $this->dfs($board, $i, $j - 1);
  34. $this->dfs($board, $i, $j + 1);
  35. }
  36. }

GO代码实现:

  1. func solve(board [][]byte) {
  2. if board == nil || len(board) == 0 {
  3. return
  4. }
  5. for i := 0; i < len(board); i++ {
  6. for j := 0; j < len(board[0]); j++ {
  7. isEdge := i == 0 || j == 0 || i == len(board) - 1 || j == len(board[0]) - 1
  8. if isEdge && board[i][j] == 'O' {
  9. dfs(board, i, j)
  10. }
  11. }
  12. }
  13. for i := 0; i < len(board); i++ {
  14. for j := 0; j < len(board[0]); j++ {
  15. if board[i][j] == 'O' {
  16. board[i][j] = 'X'
  17. }
  18. if board[i][j] == '#' {
  19. board[i][j] = 'O'
  20. }
  21. }
  22. }
  23. }
  24. func dfs(board [][]byte, i, j int) {
  25. if i < 0 || j < 0 || i >= len(board) ||
  26. j >= len(board[0]) || board[i][j] == 'X' || board[i][j] == '#' {
  27. return
  28. }
  29. board[i][j] = '#'
  30. dfs(board, i - 1, j)
  31. dfs(board, i + 1, j)
  32. dfs(board, i, j - 1)
  33. dfs(board, i, j + 1)
  34. }