题目:
Given an m x n
board
of characters and a list of strings words
, return all words on the board.
Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
Example 1:
Input: board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"] Output: ["eat","oath"]
Example 2:
Input: board = [["a","b"],["c","d"]], words = ["abcb"] Output: []
Constraints:
m == board.length
n == board[i].length
1 <= m, n <= 12
board[i][j]
is a lowercase English letter.1 <= words.length <= 3 * 104
1 <= words[i].length <= 10
words[i]
consists of lowercase English letters.- All the strings of
words
are unique.
代码:
class Solution {
public:
vector<vector<int>> d = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int h, w;
void findWord(vector<vector<char>>& board, string& cur_word, int sidx, pair<int, int> cur_pos, vector<string>& res, vector<vector<int>>& record, int& flag) {
if(sidx == cur_word.length() && !flag)
{
res.push_back(cur_word);
flag = 1;
return;
}
pair<int, int> pos;
for(int k = 0; k<4; k++)
{
pos.first = cur_pos.first + d[k][0];
pos.second = cur_pos.second + d[k][1];
if(pos.first < 0 || pos.first >= h || pos.second < 0 || pos.second >= w)
continue;
if(!record[pos.first][pos.second] && board[pos.first][pos.second] == cur_word[sidx])
{
record[pos.first][pos.second] = 1;
findWord(board, cur_word, sidx+1, pos, res, record, flag);
record[pos.first][pos.second] = 0;
}
}
return;
}
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
vector<string> res;
if(board.size() < 1 || words.size() < 1)
return res;
h = board.size();
w = board[0].size();
if(w < 1)
return res;
vector<vector<pair<int, int>>> m(26);
for(int i = 0; i<h; i++)
{
for(int j = 0; j<w; j++)
{
m[board[i][j] - 'a'].push_back(pair<int, int>(i, j));
}
}
set<string> words_unique;
for(int i = 0; i<words.size(); i++)
{
words_unique.insert(words[i]);
}
for(set<string>::iterator iter = words_unique.begin(); iter != words_unique.end(); iter++)
{
string cur_word = *iter;
if(cur_word.length() < 1)
{
res.push_back(cur_word);
continue;
}
int first_idx = cur_word[0] - 'a';
int flag = 0;
for(int l = 0; l < m[first_idx].size(); l++)
{
vector<vector<int>> record(h, vector<int>(w, 0));
pair<int, int> pos = m[first_idx][l];
record[pos.first][pos.second] = 1;
findWord(board, cur_word, 1, m[first_idx][l], res, record, flag);
record[pos.first][pos.second] = 0;
if(flag)
break;
}
}
return res;
}
};
这题的解法虽然不是很优,但是这道题是当年开启了刷题的重要里程碑~ 记得当时leetcode已经涨到了600题,感觉要刷完全部无望,就有些胆怯,迟迟没有推动刷leetcode的进程。
当年找实习,很多公司借用牛客网,作为线上写题平台OJ,我就开始在牛客上找过去的题开始做。做着做着发现,好多题都和leetcode上的一样,可以直接把解法粘过去AC。
连粘了几题之后,在这道word search上卡住了,之前的都能直接AC,到了这题就有几个案例TLE,开始纳闷,想把剩下的几个案例给通过。这才发现,原来牛客上很多题的case要少一些,不如直接刷leetcode,这才开启了正式在leetcode刷题的历程~~哈哈哈哈哈哈~所以应该感谢这道题呀~!