【刷题】LC-79:单词搜索(Word Search )

题目描述:

【刷题】LC-79:单词搜索(Word Search )_第1张图片

DFS,标准的回溯搜索。

class Solution {
    public boolean exist(char[][] board, String word) {
        int rows = board.length;
        int cols = board[0].length;
        char[] words = word.toCharArray();
        boolean[][] visited = new boolean[rows][cols];
        for (int i = 0 ; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                 if(dfs(board, words, visited, rows, cols, i ,j, 0)) {
                     return true;
                 }
            }
        }
        return false;
    }

    public boolean dfs(char[][] board, char[] words, boolean[][] visited,
                       int rows, int cols, int row, int col, int index) {
        if (index == words.length) {
            return true;
        }

        if (row < 0 || col < 0 || row >= rows || col >= cols
            || board[row][col] != words[index] || visited[row][col]) {
                return false;
        }
        visited[row][col] = true;
        boolean res = dfs(board, words, visited, rows, cols, row - 1, col, index + 1) 
                 || dfs(board, words, visited, rows, cols, row + 1, col, index + 1)
                 || dfs(board, words, visited, rows, cols, row, col - 1, index + 1)
                 || dfs(board, words, visited, rows, cols, row, col + 1, index + 1);
        
        visited[row][col] = false;
        return res;
    }
}

你可能感兴趣的:(LeetCode,深度优先,算法)