Bootstrap

LeetCode79—单词搜索(java版)

题目描述:

标签: 数组  回溯  矩阵

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

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

代码:

 思路分析:和图里的dfs搜索很像

1、对棋盘遍历,并对当前点进行dfs搜索

2、定义dfs方法即backTracing方法,首先判断当前长度是否已经等于word长度了,如果等于说明已经找到了返回true。否则,对下标进行合理校验、当前棋盘上的字符是否不等于word当前字符、当前棋盘字符是否被访问过,如果都不符合返回true,否则对棋盘上该点进行四个方向的dfs搜索。

3、区别:感觉和图的dfs区别在于,这里要在每次dfs一开始就判断是否满足返回条件。

class Solution {
    private int[][] direction = {{1,0}, {-1,0}, {0,1}, {0,-1}};
    private int m,n;

    public boolean exist(char[][] board, String word) {
        if(word == null || word.length() == 0){
            return true;
        }
        if(board == null || board.length == 0 || board[0].length == 0){
            return false;
        }
        m = board.length;
        n = board[0].length;
        boolean[][] hasVisited = new boolean[m][n];
        for(int i = 0;i < m;i++){
            for(int j = 0;j < n;j++){
                if(backTracing(0, i, j, hasVisited, board, word)){
                    return true; 
                }
            }
        }
        return false;
    }

    public boolean backTracing(int curLen, int i, int j, boolean[][] hasVisited,char[][] board, String word){
        if(curLen == word.length()){
            return true;
        }
        if(i < 0 || i >= m || j < 0 || j >= n || board[i][j] != word.charAt(curLen)
            || hasVisited[i][j]){
                return false;
        }
        hasVisited[i][j] = true;
        for(int[] d : direction){
            if(backTracing(curLen+1, i + d[0], j + d[1], hasVisited,board, word)){
                return true;
            }
        }
        hasVisited[i][j] = false;
        return false;
    }
}

 

;