题意:

image.png

解题思路:

  1. 思路:DFS深度优先搜索[回溯];
  2. 时间复杂度:(m * n) ^ 2

PHP代码实现:

  1. class Solution {
  2. /**
  3. * @param String[][] $board
  4. * @param String $word
  5. * @return Boolean
  6. */
  7. function exist($board, $word) {
  8. $x = count($board);
  9. $y = count($board[0]);
  10. for ($i = 0; $i < $x; $i++) {
  11. for ($j = 0; $j < $y; $j++) {
  12. $res = $this->do($board, $i, $j, $word, 0);
  13. if ($res) return true;
  14. }
  15. }
  16. return false;
  17. }
  18. function do($board, $i, $j, $word, $start) {
  19. if ($start >= strlen($word)) return true;
  20. if ($board[$i][$j] != $word[$start] || $i < 0
  21. || $i >= count($board) || $j < 0 || $j >= count($board[0])) {
  22. return false;
  23. }
  24. $c = $word[$start];
  25. //abcb
  26. $board[$i][$j] = "#";// 避免该位重复使用
  27. $res = ($this->do($board, $i + 1, $j, $word, $start + 1) ||
  28. $this->do($board, $i - 1, $j, $word, $start + 1) ||
  29. $this->do($board, $i, $j + 1, $word, $start + 1) ||
  30. $this->do($board, $i, $j - 1, $word, $start + 1)
  31. );
  32. $board[$i][$j] = $c;// 如果都不通,则回溯上一状态
  33. return $res;
  34. }
  35. }

GO代码实现:

  1. func exist(board [][]byte, word string) bool {
  2. m := len(board)
  3. n := len(board[0])
  4. for i := 0; i < m; i++ {
  5. for j := 0; j < n; j++ {
  6. if backtrace(board, word, i, j, 0) {
  7. return true
  8. }
  9. }
  10. }
  11. return false
  12. }
  13. func backtrace(board [][]byte, word string, i, j, k int) bool {
  14. if k == len(word) {
  15. return true
  16. }
  17. if i < 0 || j < 0 || i == len(board) || j == len(board[i]) {
  18. return false
  19. }
  20. if board[i][j] != word[k] {
  21. return false
  22. }
  23. tmp := board[i][j]
  24. // 重置为空,避免回溯时重复使用
  25. board[i][j] = byte(' ')
  26. // 向上,向下,向左,向右
  27. if backtrace(board, word, i - 1, j, k + 1) {
  28. return true
  29. }
  30. if backtrace(board, word, i + 1, j, k + 1) {
  31. return true
  32. }
  33. if backtrace(board, word, i, j - 1, k + 1) {
  34. return true
  35. }
  36. if backtrace(board, word, i, j + 1, k + 1) {
  37. return true
  38. }
  39. board[i][j] = tmp
  40. return false
  41. }