Sunday, February 23, 2020

Word Search II

Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must 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 in a word.

Example:
Input: 
board = [
  ['o','a','a','n'],
  ['e','t','a','e'],
  ['i','h','k','r'],
  ['i','f','l','v']
]
words = ["oath","pea","eat","rain"]

Output: ["eat","oath"]

Note:
  1. All inputs are consist of lowercase letters a-z.
  2. The values of words are distinct.

========= Time limit exceed with regular dfs approach =============

class Solution {
public:
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        vector<string> sol;
        if (words.size() == 0) {
            return sol;
        } 
        set<string> st(words.begin(), words.end());
        
        int rows = board.size();
        if (rows == 0) {
            return sol;
        }
        int cols = board[0].size();
        vector<vector<bool>> visited(board.size(),
                                     vector<bool>(board[0].size(), false));
        
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                dfs(board, i, j, visited, st, "", sol);
            }
        }
        return sol;
    }
    
    void dfs(vector<vector<char>>& board, int i, int j,
             vector<vector<bool>>& visited, set<string>& st, string ans,
            vector<string>& sol) {
        if (i < 0 || i == board.size() || j < 0 || j == board[0].size() ||
           visited[i][j]) {
            return;
        }
        
        ans = ans + board[i][j];
        if (st.count(ans)) {
            st.erase(ans);
            sol.push_back(ans);
            return;
        }
        
        visited[i][j] = true;
        dfs(board, i + 1, j, visited, st, ans, sol);
        dfs(board, i - 1, j, visited, st, ans, sol);
        dfs(board, i, j + 1, visited, st, ans, sol);
        dfs(board, i, j - 1, visited, st, ans, sol);
        visited[i][j] = false;
        return;
    }
};

============= Use Tries to store the dictionary and perform prefix search during dfs =
https://www.cnblogs.com/grandyang/p/4516013.html

No comments:

Post a Comment