1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| class Solution { bool dfs(vector<vector<char>> &board, int y, int x, string& s, vector<vector<bool>> &vis, int pos = 0) { if(0 <= y and y < board.size() and 0 <= x and x < board[0].size() and !vis[y][x] and board[y][x] == s[pos]) { if(pos == s.length() - 1) return true; vis[y][x] = true; int dy[8]{-1,-1,-1,0,1,1,1,0}, dx[8]{-1,0,1,1,1,0,-1,-1}; for(int i = 0; i < 8; i++) { if(dfs(board, y + dy[i], x + dx[i], s, vis, pos + 1)) { vis[y][x] = false; return true; } } vis[y][x] = false; } return false; } public: vector<string> wordBoggle(vector<vector<char>> &board, vector<string> &dictionary) { int n = board.size(), m = board[0].size(); unordered_map<char, vector<pair<int,int>>> mp; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { mp[board[i][j]].push_back({i,j}); } } vector<string> res; vector<vector<bool>> vis(n, vector<bool>(m)); for(auto& dict : dictionary) { bool search = false; for(auto& [y, x] : mp[dict[0]]) { search = dfs(board, y, x, dict, vis); if(search) break; } if(search) res.push_back(dict); } return res; } };
|