212. Word Search II가 2차원 자모표에서 주어진 워드 집합의 워드 서브열을 찾다
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;
}
};
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
0부터 시작하는 LeetCode Day8 「1302. Deepest Leaves Sum」해외에서는 엔지니어의 면접에 있어서 코딩 테스트라고 하는 것이 행해지는 것 같고, 많은 경우, 특정의 함수나 클래스를 주제에 따라 실장한다고 하는 것이 메인이다. 빠른 이야기가 본고장에서도 행해지고 있는 것 같은 코...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.