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']
]code

Given word = "ABCCED", return true. Given word = "SEE", return true.
Given word = "ABCB", return false.字符串

这是一道搜索题,用backtracking作,问题就是怎样设计这个回溯过程。
咱们须要的就是在这个二维数组里面一个个寻找每一个字符,因此dfs的终止条件是当咱们把每一个字符所有搜索了,也就是index==word.length。由于每一个字符只能使用一次因此咱们还须要一个visited数组来记录当前元素是否被访问过,若是咱们找到了和当前搜索的字符相匹配的元素,咱们就要上下左右搜索四个方向。
这么看来思路仍是很清晰的,可是我在作这一题时被几点困扰:1.咱们须要遍历二维数组,但同时咱们又须要移动移动被搜索字符串的index,一开始我是把遍历二维数组和移动字符串的index写在了同一个dfs的recursion里面而后接下去我就没办法写了,看了discuss以后才知道应该把遍历二维数组写在主函数里面,让它来调用dfs。2.选择下一个能够走的adjacent,我一开始还在想需不须要用一个list来存储每一步能够走的adjacent,这样的话就太麻烦了,还须要分状况讨论,但实际上是没有必要的。咱们把这些判断都加在recursion的终止条件里面就行了。it

代码以下:io

class Solution {
    public boolean exist(char[][] board, String word) {
        int m = board.length, n = board[0].length;
        boolean[][] visited = new boolean[m][n];
        for (int i = 0; i < board.length; i ++) {
            for (int j = 0; j < board[0].length; j ++) {
                if (word.charAt(0) == board[i][j] && dfs(board, word, visited, 0, i, j))
                    return true;
            }
        }
        return false;
    }
    public boolean dfs(char[][] board, String word, boolean[][] visited, int index, int row, int col) {
        if (index == word.length()) return true;
        if (row == board.length || row < 0 || col == board[0].length || col < 0 || visited[row][col] || word.charAt(index) != board[row][col])  return false;
        visited[row][col] = true;
        if (dfs(board, word, visited, index+1, row+1, col) ||
            dfs(board, word, visited, index+1, row, col+1) ||
            dfs(board, word, visited, index+1, row-1, col) ||
            dfs(board, word, visited, index+1, row, col-1))
            return true;
        visited[row][col] = false;
        return false;
    }
}

这道题能够对照37那道数独题,收获会更大。class

相关文章
相关标签/搜索