-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathboggle_solver.h
More file actions
93 lines (74 loc) · 2.62 KB
/
boggle_solver.h
File metadata and controls
93 lines (74 loc) · 2.62 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#ifndef BOGGLE_SOLVER_H
#define BOGGLE_SOLVER_H
#include <string>
#include <vector>
#include <set>
#include "boggle_board.h"
#include "word_tree.h"
class BoggleSolver
{
private:
const BoggleBoard *board;
const WordTree *wordTree;
void solve(const unsigned short row, const unsigned short col, const WordTree *wordTree, std::string currWord, std::set<std::string> *words);
std::vector<std::vector<bool>> visited;
public:
BoggleSolver(const BoggleBoard *b, const WordTree *wt) : board(b), wordTree(wt)
{
int size = BoggleBoard::SIZE;
std::vector<bool> row(size, false);
for (int i = 0; i < size; i++)
{
visited.push_back(row);
}
}
std::set<std::string> solve();
};
std::set<std::string> BoggleSolver::solve()
{
std::set<std::string> wordList;
for (unsigned short row = 0; row < BoggleBoard::SIZE; row++)
{
for (unsigned short col = 0; col < BoggleBoard::SIZE; col++)
{
this->solve(row, col, this->wordTree, std::string(""), &wordList);
}
}
return wordList;
}
void BoggleSolver::solve(const unsigned short row, const unsigned short col, const WordTree *wordTree, std::string currWord, std::set<std::string> *words)
{
this->visited[row][col] = true;
if (wordTree->isWord) {
words->insert(currWord);
}
// for each of the adjacent cells
for (short row_offset = -1; row_offset <= 1; row_offset++)
{
for (short col_offset = -1; col_offset <= 1; col_offset++)
{
if (col_offset == 0 && row_offset == 0) continue; // cell goes to itself
// get character
const unsigned short board_row = (short) row - row_offset;
const unsigned short board_col = (short) col - col_offset;
// out of bounds check
if (board_row >= BoggleBoard::SIZE || board_col >= BoggleBoard::SIZE)
continue;
// already visited
if (this->visited[board_row][board_col])
continue;
// converts adjacent cell's character to WordTree index
char cellLetter = this->board->board[board_row][board_col];
unsigned int char_to_index = cellLetter - 'a';
if (wordTree->paths[char_to_index]) {
const WordTree *child = wordTree->paths[char_to_index];
//recursively solve
std::string newWord = std::string(currWord);
newWord += cellLetter;
solve(board_row, board_col, child, newWord, words);
}
}
}
this->visited[row][col] = false;
}
#endif