【LeetCode】解题79:Word Search

Problem 79: Word Search [Medium]

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

来源:LeetCode

解题思路

基本思路为深度优先搜索,搜索过的位置需要occupy,防止重复使用。

  • 遍历数组,使用backtracking函数递归搜索该位置是否能满足字符串。
  • backtracking()中首先比较当前位置board[i][j]的字符是否与字符串中需要匹配的字符word[search]一致。
    a. 如果不一致,返回false。
    b. 如果一致,occupy[i][j]设为true,递归搜索邻近的四个方向board[i-1][j],board[i+1][j],board[i][j-1],board[i][j+1],有某个方向上的返回值为true就返回true,如果四个方向都是false则返回false。
  • 注意:如果该位置最终结果不符合要求,需要释放占领的字符,即occupy[i][j]重新设为false。

参考:LeetCode题解

要点:回溯算法深度优先

Solution (Java)

代码一:

class Solution {
    private boolean[][] occupy;
    private int[][] direction = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; // up down left right

    public boolean exist(char[][] board, String word) {
        int m = board.length;
        int n = board[0].length;
        occupy = new boolean[m][n];

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (backtracking(board, i, j, m, n, word, 0)) return true;
            }
        }
        return false;
    }

    private boolean backtracking(char[][] board, int i, int j, int m, int n, String word, int search) {
        if (board[i][j] == word.charAt(search)) {
            if(search == word.length() - 1) return true;
            occupy[i][j] = true;
            for (int k = 0; k < 4; k++) {
                int nextx = i + direction[k][0];
                int nexty = j + direction[k][1];
                if (nextx >= 0 && nextx < m && nexty >= 0 && nexty < n && !occupy[nextx][nexty]) {
                    if (backtracking(board, nextx, nexty, m, n, word, search + 1)) return true;
                }
            }
            occupy[i][j] = false;
        }
        return false;
    }
}

代码二:
使用String存储board,并在原位将搜索过的位置上字符串设为’#’,然后递归搜索。省去了occupy数组,但由于一开始二重循环整个数组,会导致需要很多额外的时间:

class Solution {
    public boolean exist(char[][] board, String word) {
        int m = board.length;
        int n = board[0].length;
        //int len = word.length();
        String strboard = new String();
        List<Integer> start = new ArrayList<Integer>();
        int index = 0;
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                strboard += board[i][j];
                if(board[i][j] == word.charAt(0)){
                    start.add(index);
                }
                index++;
            }
        }
        //System.out.println(strboard);
        for(int i = 0; i < start.size(); i++){
            if(backtracking(strboard, start.get(i), m, n, word, 1)) return true;
        }
        return false;
    }
    private boolean backtracking(String board, int start, int m, int n, String word, int search){
        if(search == word.length()) return true;
        String newboard = board.substring(0, start) + '#' + board.substring(start+1);
        // up
        if(start / n > 0){
            if(board.charAt(start - n) == word.charAt(search)){
                if(backtracking(newboard, start-n, m, n, word, search+1)) return true;
            }
        }
        // down
        if(start / n < m - 1){
            if(board.charAt(start + n) == word.charAt(search)){
                if(backtracking(newboard, start+n, m, n, word, search+1)) return true;
            }
        }
        // left
        if(start % n > 0){
            if(board.charAt(start - 1) == word.charAt(search)){
                if(backtracking(newboard, start-1, m, n, word, search+1)) return true;
            }
        }
        // right
        if(start % n < n - 1){
            if(board.charAt(start + 1) == word.charAt(search)){
                if(backtracking(newboard, start+1, m, n, word, search+1)) return true;
            }
        }
        return false;
    }
}

修改过程

  • 一开始使用String的方法(代码二),运行时间非常久,因此去参考了题解,发现主要区别在多了一次两重循环。
  • 代码一中一开始设置if(search == word.length()) return true;也就是直到最后一个字符匹配完毕后的下一次递归才返回true,这样会导致只有一个字符的borad无论怎样都返回false,因为上下左右没有下一个字符可以递归搜索。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值