212. Word Search II (backtracking)

ๅฆ‚ๆžœไธ็”จ trie, ๅฏไปฅๆ”นๆˆ็”จ set + DFS backtracking

time: O(N*m*n*4^k)

ๆฏๅ€‹ๅญ—๏ผš N

dfs board : mn ๆฌก ๅœจ4้€š่ทฏๅ‡บๅŽปๆ‰พ๏ผˆๆฃ‹็›คไธŠๆฏๅ€‹้ปž้ƒฝ่ฆ4ๆ–นๅ‘ๅ‡บๅŽป๏ผ‰ๆฏๅ€‹ๅ–ฎ่ฉž้ƒฝ่ฆ4ๅ€‹ๆ–นๅ‘๏ผŒๆ‰€ไปฅ4^k็ต„ๅˆ

space: O(mn+some set string space)

class Solution {
    private int directions[][] = {{0,1},{1,0},{0,-1},{-1,0}};
    public List<String> findWords(char[][] board, String[] words) {
        
        if (board == null || board.length == 0 || board[0] == null || board[0].length == 0) {
            return new ArrayList<>();
        }
        int m = board.length;
        int n = board[0].length;
        
        Set<String> res = new HashSet<>();
        Set<String> wordSet = new HashSet<>();
        Set<String> prefix = new HashSet<>();
        for (String word : words) {
            for (int i = 0; i < word.length(); i++) {
                prefix.add(word.substring(0, i+1));
            }
            wordSet.add(word);
        }
        
        
        boolean visited[][] = new boolean[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                visited[i][j] = true;
                dfs(res, board, wordSet, prefix, String.valueOf(board[i][j]), visited, i, j);
                visited[i][j] = false;
            }
        }
        
        return new ArrayList<>(res);
    }
    private void dfs(Set<String> res, char[][] board, Set<String> wordSet, Set<String> prefix, String word, boolean visited[][], int i, int j) {
        if (!prefix.contains(word)) {
            return;
        }
        if (wordSet.contains(word)) {
            res.add(word);
        }
        for (int direction[] : directions) {
            int newX = i + direction[0];
            int newY = j + direction[1];
            if (!isInside(board, newX, newY) || visited[newX][newY]) {
                continue;
            }
            visited[newX][newY] = true;
            String newWord = word + String.valueOf(board[newX][newY]);
            dfs(res, board, wordSet, prefix, newWord, visited, newX, newY);
            visited[newX][newY] = false;
        }
    }
    private boolean isInside(char[][] board, int x, int y) {
        return (x >= 0 && x < board.length && y >=0 && y < board[0].length);
    }
}
/*
DFS
if not use trie, 
use set to store prefix

if (word not in prefix) continue; 

DO DFS
*/

Last updated