Leetcode 212. Word Search II | | Leetcode 212. Word Search II 文章作者:Tyan博客:noahsnail.com | CSDN | 简书 1. Description 2. Solution1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253class Solution {public: vector<string> findWords(vector<vector<char>>& board, vector<string>& words) { vector<string> result; int rows = board.size(); int columns = board[0].size(); unordered_set<string> s; for(string word : words) { s.insert(word); } for(string word : s) { if(rows * columns < word.length()) { continue; } if(exist(board, word, rows, columns)) { result.push_back(word); } } return result; } private: bool exist(vector<vector<char>>& board, string& word, int& rows, int& columns) { for(int i = 0; i < rows; i++) { for(int j = 0; j < columns; j++) { if(board[i][j] == word[0] && search(board, word, i, j, 0, rows, columns)) { return true; } } } return false; } bool search(vector<vector<char>>& board, string& word, int i, int j, int current, const int& rows, const int& columns) { if(i < 0 || i == rows || j < 0 || j == columns || board[i][j] != word[current]) { return false; } board[i][j] -= 60; current += 1; if(current == word.length()) { board[i][j] += 60; return true; } bool result = search(board, word, i + 1, j, current, rows, columns) || search(board, word, i - 1, j, current, rows, columns) || search(board, word, i, j + 1, current, rows, columns) || search(board, word, i, j - 1, current, rows, columns); board[i][j] += 60; return result; } }; Reference https://leetcode.com/problems/word-search-ii/description/ 如果有收获,可以请我喝杯咖啡! 赏 微信打赏 支付宝打赏