[AlgoExpert] Boggle Board

Boggle Board

  • Time : O(nm s 8 ^(maxlen(s))
  • Space : O(nm)
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
40
#include <vector>
using namespace std;

bool dfs(vector<vector<char>>& board, int y, int x, string& w, vector<vector<bool>>& vis, int pos) {
if(pos == w.length()) return true;
if(0 <= y and y < board.size() and 0 <= x and x < board[0].size() and !vis[y][x]) {
if(board[y][x] != w[pos]) return false;
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++) {
int ny = y + dy[i], nx = x + dx[i];
if(dfs(board,ny,nx,w,vis,pos+1)) {
vis[y][x] = false;
return true;
}
}
vis[y][x] = false;
}
return false;
}

vector<string> boggleBoard(vector<vector<char>> board, vector<string> words) {
int n = board.size(), m = board[0].size();
vector<string> res;
vector<vector<bool>> vis(n, vector<bool>(m));
for(auto& w : words) {
bool find = false;
for(int i = 0; i < n and !find; i++) {
for(int j = 0; j < m and !find; j++) {
if(board[i][j] == w[0]) {
find = dfs(board,i,j,w,vis,0);
}
}
}
if(find)
res.push_back(w);
}
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/11/PS/AlgoExpert/boggle-board/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.