leetcode----79. Word Search

链接:

https://leetcode.com/problems/word-search/

大意:

给定一个由字符组成的二维矩阵b,以及一个单词word,判断word是否存在二维矩阵b中。在二维矩阵中,每个位置只能前后或者上下移动。例子:

思路:

图的dfs,也即回溯法。

代码:

class Solution {
    public boolean exist(char[][] b, String word) {
        if (b.length == 0 || b.length * b[0].length < word.length())
            return false;
        char[] str = word.toCharArray();
        boolean[][] visited = new boolean[b.length][b[0].length];
        for (int i = 0; i < b.length; i++) {
            for (int j = 0; j < b[0].length; j++) {
                if (exist(b, i, j, str, 0, visited))
                    return true;
            }
        }
        return false;
    }
    // index为str的当前下标   row,col为b的行和列
    public boolean exist(char[][] b, int row, int col, char[] str, int index, boolean[][] visited) {
        if (row < 0 || row >= b.length || col < 0 || col >= b[0].length || visited[row][col])
            return false;
        visited[row][col] = true;
        if (b[row][col] == str[index]) {
            // 当前比较的为str的最后一个字符
            if (index == str.length - 1)
                return true;
            // 上下左右进行dfs
            boolean tag =  exist(b, row - 1, col, str, index + 1, visited)
                || exist(b, row + 1, col, str, index + 1, visited)
                || exist(b, row, col - 1, str, index + 1, visited)
                || exist(b, row, col + 1, str, index + 1, visited);
            visited[row][col] = false; //回溯
            return tag; // 返回结果之前需要回溯
        } else {
            visited[row][col] = false; // 回溯
            return false;
        }
    }
}

结果:

结论:

dfs=回溯 

 

 

猜你喜欢

转载自blog.csdn.net/smart_ferry/article/details/88966278