aboutsummaryrefslogtreecommitdiff
path: root/word_search2.cpp
blob: 8163966e6844268139272559b9c606b2c68ce698 (plain)
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
#include "leetcode.h"

struct Trie {
  bool isEnd;
  string word;
  Trie *child[26];
  Trie() {
    isEnd = false;
    word = "";
    for (int i = 0; i < 26; i++)
      child[i] = NULL;
  }
};

class Solution {
public:
  vector<string> ans;
  vector<string> findWords(vvd(char) & board, vector<string> &words) {
    int n = board.size(), m = board[0].size();
    for (auto w : words)
      insert(w);
    for (int i = 0; i < n; i++)
      for (int j = 0; j < m; j++)
        dfs(board, i, j, n, m, root);
    return ans;
  }

private:
  vector<int> dx = {-1, 0, 1, 0}, dy = {0, 1, 0, -1};
  Trie *root = new Trie();
  void insert(string &s) {
    int n = s.size();
    Trie *curr = root;
    for (int i = 0; i < n; i++) {
      int idx = s[i] - 'a';
      if (curr->child[idx] == NULL)
        curr->child[idx] = new Trie();
      curr = curr->child[idx];
    }
    curr->isEnd = true;
    curr->word = s;
  }
  void dfs(vvd(char) & board, int i, int j, int n, int m, Trie *curr) {
    if (i < 0 || i >= n || j < 0 || j >= m || board[i][j] == '#')
      return;
    int idx = board[i][j] - 'a';
    if (curr->child[idx] == NULL)
      return;
    curr = curr->child[idx];
    if (curr->isEnd) {
      ans.push_back(curr->word);
      curr->isEnd = false;
    }
    char val = board[i][j];
    board[i][j] = '#';
    for (int k = 0; k < 4; k++) {
      int newI = i + dx[k], newJ = j + dy[k];
      dfs(board, newI, newJ, n, m, curr);
    }
    board[i][j] = val;
  }
};

int main() {
  Solution obj;
  vvd(char) board = {{'a', 'b'}, {'c', 'd'}};
  vector<string> words = {"abcb"};
  for (auto i : obj.findWords(board, words))
    cout << i << endl;
}