212. Word Search II가 2차원 자모표에서 주어진 워드 집합의 워드 서브열을 찾다

5994 단어 leetcodedp
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.
For example, Given words =  ["oath","pea","eat","rain"]  and board =
[
  ['o','a','a','n'],
  ['e','t','a','e'],
  ['i','h','k','r'],
  ['i','f','l','v']
]

Return  ["eat","oath"]
.
1. 나의 해답 순수 dfs 시간 초과
//
//  main.cpp
//  212. Word Search II
//
//  Created by zjl on 16/10/11.
//  Copyright © 2016  zjl. All rights reserved.
//

#include 
#include 
using namespace std;

int orinal[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};

bool find_res(vector>board, string word, vector>&visit, int level, int row, int col){
    
    if(word[level] != board[row][col]) return false;
    
    if(level == word.size()-1)
        return true;
    
    visit[row][col] = true;
    int rows = board.size(), cols = board[0].size();
    for(int i = 0; i < 4; i++){
        int r = row + orinal[i][0];
        int c = col + orinal[i][1];
        if(r >= 0 && r < rows && c >= 0 && c < cols && visit[r][c] == false){
            bool  b = find_res(board, word, visit, level+1, r,c);
            if(b){
                visit[row][col] = false;
                return true;
            }
        }
    }
    visit[row][col] = false;
    return false;
}

vector findWords(vector>& board, vector& words) {
    vectorres;
    if(board.size() == 0 || board[0].size() == 0 || words.size() == 0) return res;
    int row = board.size();
    int col = board[0].size();
    int len = words.size();
    vector>visit(row, vector(col, false));
    for(int k= 0; k < len; k++){
        bool b = false;
        for(int i = 0; i < row; i++){
            for(int j = 0; j < col; j++){
                if(find_res(board, words[k], visit, 0, i, j)){
                    b = true;
                    break;
                }
            }
            if(b) break;
        }
        if(b){
            res.push_back(words[k]);
            
        }
    }
    //  
    sort(res.begin(), res.end());
    res.erase(unique(res.begin(), res.end()), res.end());
    return res;
}

int main(int argc, const char * argv[]) {
    // insert code here...
    vector> board= {{'o','a','a','n'},{'e','t','a','e'},{'i','h','k','r'},{'i','f','l','v'}};
    vector words = {"oath","pea","eat","rain"};
    //vector> board= {{'a'}};
    //vector words = {"a"};
    vector res = findWords(board, words);
    for(auto a: res)
        cout<

2. 모든 문자열을 2차원 그룹으로 옮겨다니지 않아도 된다. 즉, 주어진 문자열을Trie 트리에 저장한 다음 2차원 그룹을 옮겨다닐 때 문자열을 찾는다.
자기가 옳다고 생각했는데 시간이 초과돼서 다른 사람과 코드를 비교해 봐도 괜찮을 것 같은데...그럼 나중에 해결할게요.
class Solution {
private:
    int orinal[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};
public:
    struct TrieNode{
      TrieNode* next[26];
      string word;//                 string ,    string    
    };
    
    TrieNode* buildTrie(vectorwords){
        TrieNode* p = new TrieNode();
        for(int i = 0; i < words.size(); i++){
            string s = words[i];
            TrieNode* root = p;
            for(int j = 0; j < s.size(); j++){
                if(root->next[s[j]-'a'] == NULL) root->next[s[j]-'a'] = new TrieNode();
                root = root->next[s[j] - 'a'];
            }
            root->word = s;//                 
        }
        return p;
    }
    
    
    void find_res(vector>board, TrieNode* p, int row, int col,vector&res){
    
    char c = board[row][col];
    //           p      
    if(board[row][col]=='#' || p->next[c-'a'] == NULL) return;
    
    p = p->next[c-'a'];
    //visit[row][col] = true;
    board[row][col] = '#';
    if(!p->word.empty()){
        res.push_back(p->word);
        p->word.clear(); //      
    }
    
    int rows = board.size(), cols = board[0].size();
    for(int i = 0; i < 4; i++){
        int r = row + orinal[i][0];
        int c = col + orinal[i][1];
        if(r >= 0 && r < rows && c >= 0 && c < cols){
            find_res(board, p, r,c, res);
        }
    }
    //visit[row][col] = false;
    board[row][col] = c;
}


vector findWords(vector>& board, vector& words) {
    vectorres;
    if(board.size() == 0 || board[0].size() == 0 || words.size() == 0) return res;
    int row = board.size();
    int col = board[0].size();
    int len = words.size();
    TrieNode* root = buildTrie(words);
    //vector>visit(row, vector(col, false));

    for(int i = 0; i < row; i++){
        for(int j = 0; j < col; j++){
            find_res(board, root, i, j, res);
        }
    }
    
    return res;
}

};

좋은 웹페이지 즐겨찾기