您的位置:首页 > 其它

Leetcode -- Word Search II

2015-10-26 21:42 405 查看
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"]
.

Note:

You may assume that all inputs are consist of lowercase letters
a-z
.

分析:

本题采用trie结构求解,可以降低运算量。有关trie的相关内容参考 点击打开链接有关内容。

class Solution {
public:
set<string> res;
Trie trie;
int dif[4][2]={{0,-1},{0,1},{-1,0},{1,0}};
int n,m;
void dfs(vector<vector<char>>& board,vector<vector<bool>> vis,string cur,int x,int y)
{
if(trie.search(cur))
res.insert(cur);
vis[x][y]=1;
for(int i=0;i<4;++i)
{
int xx=x+dif[i][0],yy=y+dif[i][1];
if(xx>=0&&xx<n&&yy>=0&&yy<m&&vis[xx][yy]==0)
{
if(trie.startsWith(cur+board[xx][yy]))
dfs(board,vis,cur+board[xx][yy],xx,yy);
}
}
}
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
for(int i=0;i<words.size();++i)
trie.insert(words[i]);
n=board.size(),m=board[0].size();
vector<vector<bool>> vis(n,vector<bool>(m,0));
for(int i=0;i<n;++i)
for(int j=0;j<m;++j)
{
string s;
s+=board[i][j];
if(trie.startsWith(s))
dfs(board,vis,s,i,j);
}
vector<string> final;
for(auto &str:res)
final.push_back(str);
return final;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: