aboutsummaryrefslogtreecommitdiff
path: root/word_search.cpp
blob: bbd072f3b262b2f61cfe8db333d32e331afeebd9 (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
#include "leetcode.h"

class Solution {
public:
  bool exist(vvd(char) & board, string word) {
    int dirs[5] = {0, -1, 0, 1, 0};
    map<char, int> cnt;
    int m = board.size(), n = board[0].size(), l = word.size();

    for (char c : word)
      cnt[c] += 1;

    if (cnt[word[0]] > cnt[word[l - 1]])
      reverse(word.begin(), word.end());

    function<bool(int, int, int)> dfs;
    dfs = [&](int i, int j, int s) -> bool {
      if (s == l)
        return true;

      if (i < 0 or i >= m or j < 0 or j >= n)
        return false;
      if (board[i][j] != word[s])
        return false;

      board[i][j] = '#';
      for (int d = 0; d < 4; ++d)
        if (dfs(i + dirs[d], j + dirs[d + 1], s + 1))
          return true;
      board[i][j] = word[s];

      return false;
    };

    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j)
        if (dfs(i, j, 0))
          return true;

    return false;
  }
};

int main() {
  Solution obj;
  vvd(char) board = {
      {'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A', 'D', 'E', 'E'}};
  string word = "ABCCED";
  if (obj.exist(board, word))
    cout << "true";
  else
    cout << "false";
}