LeetCode-in-Dart

Medium

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:

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

Solution

class Solution {
  bool backtrace(List<List<String>> board, List<List<bool>> visited,
      String word, int index, int x, int y) {
    if (index == word.length) {
      return true;
    }
    if (x < 0 || x >= board.length || y < 0 || y >= board[0].length ||
        visited[x][y]) {
      return false;
    }
    visited[x][y] = true;

    if (word[index] == board[x][y]) {
      bool res =
          backtrace(board, visited, word, index + 1, x, y + 1) ||
              backtrace(board, visited, word, index + 1, x, y - 1) ||
              backtrace(board, visited, word, index + 1, x + 1, y) ||
              backtrace(board, visited, word, index + 1, x - 1, y);

      if (!res) {
        visited[x][y] = false;
      }
      return res;
    } else {
      visited[x][y] = false;
      return false;
    }
  }

  bool exist(List<List<String>> board, String word) {
    List<List<bool>> visited = List.generate(
        board.length, (_) => List.filled(board[0].length, false));

    for (int i = 0; i < board.length; i++) {
      for (int j = 0; j < board[0].length; j++) {
        if (backtrace(board, visited, word, 0, i, j)) {
          return true;
        }
      }
    }
    return false;
  }
}