题目

给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。

单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。

示例 1: image.png

输入:board = [[“A”,”B”,”C”,”E”],[“S”,”F”,”C”,”S”],[“A”,”D”,”E”,”E”]], word = “ABCCED”
输出:true

示例 2: image.png

输入:board = [[“A”,”B”,”C”,”E”],[“S”,”F”,”C”,”S”],[“A”,”D”,”E”,”E”]], word = “SEE”
输出:true

示例 3:

输入:board = [[“A”,”B”,”C”,”E”],[“S”,”F”,”C”,”S”],[“A”,”D”,”E”,”E”]], word = “ABCB”
输出:false

提示:

m == board.length
n = board[i].length
1 <= m, n <= 6
1 <= word.length <= 15
board 和 word 仅由大小写英文字母组成

进阶:你可以使用搜索剪枝的技术来优化解决方案,使其在 board 更大的情况下可以更快解决问题?

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/word-search
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

对每个字符和word首字母相同的格子进行dfs搜索,找到一条和word匹配的路径就返回true。

下面是带返回值的写法,写法中规中矩,基本就是回溯的模板写法。

代码

  1. class Solution {
  2. int[][] dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
  3. public boolean exist(char[][] board, String word) {
  4. int m = board.length;
  5. int n = board[0].length;
  6. for (int i = 0; i < m; i++) {
  7. for (int j = 0; j < n; j++) {
  8. if (board[i][j] == word.charAt(0)) {
  9. Deque<Character> path = new ArrayDeque<>();
  10. boolean[][] visited = new boolean[m][n];
  11. if (dfs(i, j, m, n, board, word, visited, 0)) {
  12. return true;
  13. }
  14. }
  15. }
  16. }
  17. return false;
  18. }
  19. private boolean dfs(int r, int c, int m, int n, char[][] board, String word, boolean[][] visited, int index) {
  20. if (index == word.length()) {
  21. return true;
  22. }
  23. if (r < 0 || r >= m || c < 0 || c >= n || word.charAt(index) != board[r][c] || visited[r][c]) {
  24. return false;
  25. }
  26. boolean res = false;
  27. visited[r][c] = true;
  28. for (int[] dir : dirs) {
  29. int nr = r + dir[0];
  30. int nc = c + dir[1];
  31. res |= dfs(nr, nc, m, n, board, word, visited, index + 1);
  32. }
  33. visited[r][c] = false;
  34. return res;
  35. }
  36. }