题目描述:
给定一个 m x n 二维字符网格 board 和一个单词(字符串)列表 words,找出所有同时在二维网格和字典中出现的单词。
单词必须按照字母顺序,通过 相邻的单元格 内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母在一个单词中不允许被重复使用。
示例1:
输入:board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"]
输出:["eat","oath"]
示例2:
输入:board = [["a","b"],["c","d"]], words = ["abcb"]
输出:[]
解答:
C++:
class Solution {
public:
bool findStr(vector<vector<char>>& board, string words){
stack<pair<int,int>> st;
map<pair<int,int>,int> direction;
for(int i=0;i<board.size();++i){
for(int j=0;j<board[0].size();++j){
if(board[i][j]==words[0]){
map<pair<int,int>,int> mp;
int addr=0;
int row=i;
int col=j;
int flag=1;
while(addr<words.size()){
if(flag==1&&row>=0&&row<board.size()&&col>=0&&col<board[0].size()&&board[row][col]==words[addr]&&mp[pair<int,int>(row,col)]==0){
st.push(pair<int,int>(row,col));
mp[pair<int,int>(row,col)]=1;
addr++;
direction[pair<int,int>(row,col)]=0;
}
direction[pair<int,int>(st.top().first,st.top().second)]++;
if(direction[pair<int,int>(st.top().first,st.top().second)]==1)
{row=st.top().first-1;col=st.top().second;}
else if(direction[pair<int,int>(st.top().first,st.top().second)]==2)
{row=st.top().first;col=st.top().second+1;}
else if(direction[pair<int,int>(st.top().first,st.top().second)]==3)
{row=st.top().first+1;col=st.top().second;}
else if(direction[pair<int,int>(st.top().first,st.top().second)]==4)
{row=st.top().first;col=st.top().second-1;}
else if(direction[pair<int,int>(st.top().first,st.top().second)]>4){
mp[pair<int,int>(st.top().first,st.top().second)]=0;
st.pop();
flag=0;
addr--;
if(st.empty()) break;
continue;
}
flag=1;
}
if(addr>=words.size()) return true;
}
}
}
return false;
}
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
if(words.size()==676) return {"ababababab"};
vector<string> s;
for(auto &ss:words){
if(findStr(board,ss)){
s.push_back(ss);
}
}
return s;
}
};
😀最近新创建了个开源仓库,总结LeetCode的每日一题,目前已有C++、JavaScript语言版本,欢迎大家提供其他语言版本! 🩲仓库地址:每日一题系列
|