LeetCode 79. Word Search 单次搜索

题目:

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

Example:
board =
[
[‘A’,‘B’,‘C’,‘E’],
[‘S’,‘F’,‘C’,‘S’],
[‘A’,‘D’,‘E’,‘E’]
]
Given word = “ABCCED”, return true.
Given word = “SEE”, return true.
Given word = “ABCB”, return false.

Constraints:

  • board and word consists only of lowercase and uppercase English letters.
  • 1 <= board.length <= 200
  • 1 <= board[i].length <= 200
  • 1 <= word.length <= 10^3

解答:

本题应采用递归的方法,通过递归对每一个数值及每一条路径进行深度遍历。

  1. 为了避免重复路径的搜索以及剪枝的需要,设置 boolean 二维数组,用于记录矩阵中某个位置是否被访问过,若访问过则对应位置变为 true
  2. 利用 Recursive() 回溯进行递归判断。其中 i、j 表示当前访问的二维数组元素位置,len 表示当前搜索的字符串 word 的索引位置
  3. 若当前索引长度 len == 字符串长度,则说明匹配成功,return true
  4. 若出现:①数组越界,②该点已访问过,③该点的字符和word中对应的 len 字符不匹配
    ,则对路径进行剪枝,进行下一个路径判断
  5. 若当前路径可以匹配,则将当前位置的 boolean 二维数组改为 true,并从当前位置的上下左右,进行下一次递归判断

具体代码实现如下:

class Solution {
    public boolean exist (char[][] board, String word) {
        int row = board.length;
        int column = board[0].length;
        boolean[][] used = new boolean[row][column];
        for(int i=0; i<row; i++) {
            for(int j=0; j<column; j++) {
                if(Recursive(board, word, used, i, j, 0)) {
                    return true;
                }
            }
        }
        return false;
    }
    private boolean Recursive (char[][] board, String word, boolean[][] used, int i, int j, int len) {
        int row = board.length;
        int column = board[0].length;
        if(len == word.length()) {
            return true;
        }
        if(i<0 || i>=row || j<0 || j>=column || used[i][j] || board[i][j]!=word.charAt(len)) {
            return false;
        }
        used[i][j] = true;
        if(Recursive(board, word, used, i+1, j, len+1) || Recursive(board, word, used, i-1, j, len+1) || Recursive(board, word, used, i, j+1, len+1) || Recursive(board, word, used, i, j-1, len+1)) {
            return true;
        }
        used[i][j] = false;
        return false;
    }
}

你可能感兴趣的:(LeetCode)