212. 单词搜索 II
题目描述:
给定一个 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;//哈希表记录该字母下标未探索的方向 1,2,3,4分别代表上,右,下,左
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;//标志位弹出顶部元素时不需要判断此时的row,col的字符符不符合要求,需要把栈顶元素改方向探索
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;
}
//addr++;
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"};//忽略41示例
vector<string> s;
for(auto &ss:words){
if(findStr(board,ss)){//依次判断单词
s.push_back(ss);
}
}
return s;
}
};
😀最近新创建了个开源仓库,总结LeetCode的每日一题,目前已有C++、JavaScript语言版本,欢迎大家提供其他语言版本!
🩲仓库地址:每日一题系列