codekofi
← All problems

Problem 51

Medium

1 · Worked examples

0 / 3

Type an input and write what you think is the output . Each problem is converted to Web Assembly, so any possible input will show the corresponding output. Only correct predictions count.

solution()
returns

2 · Which problem is it?

Locked until you have predicted 3 outputs correctly.

The accepted solution

1bool hunt(vector<string>& grid, int r, int c,
2 const string& word, int i) {
3
4 int rows = grid.size();
5 int cols = grid[0].size();
6 int len = word.size();
7
8 if (i == len) {
9 return true;
10 }
11
12 if (r < 0 || r >= rows || c < 0 || c >= cols) {
13 return false;
14 }
15
16 if (grid[r][c] != word[i]) {
17 return false;
18 }
19
20 char ch = grid[r][c];
21 grid[r][c] = '*';
22
23 bool found = hunt(grid, r + 1, c, word, i + 1) ||
24 hunt(grid, r - 1, c, word, i + 1) ||
25 hunt(grid, r, c + 1, word, i + 1) ||
26 hunt(grid, r, c - 1, word, i + 1);
27
28 grid[r][c] = ch;
29
30 return found;
31}
32
33bool solution(vector<string> grid, const string& word) {
34
35 if (word.empty()) {
36 return true;
37 }
38
39 if (grid.empty() || grid[0].empty()) {
40 return false;
41 }
42
43 int rows = grid.size();
44 int cols = grid[0].size();
45
46 for (int r = 0; r < rows; r++) {
47 for (int c = 0; c < cols; c++) {
48
49 if (hunt(grid, r, c, word, 0)) {
50 return true;
51 }
52 }
53 }
54
55 return false;
56}

Names have been stripped. The signature is the only clue you get for free. Compiled as C++20 with the standard headers and using namespace std; already in scope.