Word Search

题目地址:
https://leetcode.com/problems/word-search/#/description

题目:
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.
For example,
Given board =
[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

解题思路:
这道题是比较常规的dfs,先找到第一个match的char,然后向4个方向找。follow up:如果需要找到所有的root-leaf的路径,那么就需要建一个Pair的class,里面有i和j,那么就需要dfs返回List<List<Pair>>,如果没找到就返回null。

代码:

public boolean exist(char[][] board, String word) {
    if(board == null || board.length == 0 || board[0].length == 0){
        return false;
    }
    int m = board.length;
    int n = board[0].length;
    boolean rst = false;
    for(int i = 0; i <= m - 1; i++){
        for(int j = 0; j <= n - 1; j++){
            if(word.charAt(0) == board[i][j]){
                rst = dfs(board, word, i, j, m, n, 0);
                if(rst){
                    return rst;
                }
            }
        }
    }
    return rst;
}
private boolean dfs(char[][] board, String word, int i, int j, int m, int n, int index) {
    if(index == word.length()){
        return true;
    }
    if(i <= -1 || j <= -1 || i >= m || j >= n || board[i][j] != word.charAt(index)){
        return false;
    }
    char temp = board[i][j];
    board[i][j] = '#';
    boolean rst = dfs(board, word, i + 1, j, m, n, index + 1) || dfs(board, word, i - 1, j, m, n, index + 1) ||dfs(board, word, i, j + 1, m, n, index + 1) ||dfs(board, word, i, j - 1, m, n, index + 1);
    board[i][j] = temp;
    return rst;
}













Comments

Popular Posts