2022-11-24 Daily Challenge

Today I have done leetcode's November LeetCoding Challenge with cpp.

November LeetCoding Challenge 24

Description

Word Search

Given an m x n grid of characters board and a string word, return true if word exists in the grid.

The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.

 

Example 1:

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output: true

Example 2:

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
Output: true

Example 3:

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
Output: false

 

Constraints:

  • m == board.length
  • n = board[i].length
  • 1 <= m, n <= 6
  • 1 <= word.length <= 15
  • board and word consists of only lowercase and uppercase English letters.

 

Follow up: Could you use search pruning to make your solution faster with a larger board?

Solution

struct TrieNode {
  bool end = false;
  TrieNode *child[128] = {};
};
void insert(TrieNode *root, string word) {
  TrieNode *cur = root;
  for(auto c : word) {
    if(!cur->child[c]) {
      cur->child[c] = new TrieNode();
    }
    cur = cur->child[c];
  }
  cur->end = true;
}
constexpr int moves[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
class Solution {
  vector<vector<bool>> vis;
  vector<string> words;
  string current;
  int rows;
  int cols;
  void solve(vector<vector<char>>& board, TrieNode *root, int row, int col) {
    root = root->child[board[row][col]];
    vis[row][col] = true;
    current.push_back(board[row][col]);
    if(root) {
      if(root->end) words.push_back(current);
      for(int i = 0; i < 4; ++i) {
        int newRow = row + moves[i][0];
        int newCol = col + moves[i][1];
        if(newRow < 0 || newCol < 0 || newRow >= rows || newCol >= cols) continue;
        if(vis[newRow][newCol]) continue;
        solve(board, root, newRow, newCol);
      }
    }
    vis[row][col] = false;
    current.pop_back();
  }
public:
  bool exist(vector<vector<char>>& board, string word) {
    TrieNode *root = new TrieNode();
    rows = board.size();
    cols = board.front().size();
    vis.resize(rows, vector<bool>(cols));
    insert(root, word);
    for(int i = 0; i < rows; ++i) {
      for(int j = 0; j < cols; ++j) {
        solve(board, root, i, j);
      }
    }
    return words.size();
  }
};

// Accepted
// 84/84 cases passed (724 ms)
// Your runtime beats 48.74 % of cpp submissions
// Your memory usage beats 5.54 % of cpp submissions (9.4 MB)