TIC
The Interns Company

Word Search

MediumAcceptance: 38.9%

Problem Statement

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.

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

Input Format:

  • An m x n grid of characters 'board'
  • A string 'word'

Output Format:

  • Return true if word exists in the grid, otherwise return false

Examples:

Example 1:

Input:

board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"

Output:

true

Explanation:

The word 'ABCCED' can be constructed by going from A → B → C → C → E → D.

Example 2:

Input:

board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"

Output:

true

Explanation:

The word 'SEE' can be constructed by going from S → E → E.

Example 3:

Input:

board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"

Output:

false

Explanation:

The word 'ABCB' cannot be constructed because the letter 'B' would be used twice.

Solutions

Backtracking DFS

Time: O(m*n*4^L)
Space: O(L)

Use depth-first search from each cell in the grid as a starting point. Explore in all four directions recursively while ensuring each cell is used only once.

Optimized Backtracking

Time: O(m*n*4^L)
Space: O(L)

Enhance the backtracking algorithm with additional optimizations such as checking character frequency and pruning paths early.

Algorithm Walkthrough

Example input: nums = []

Step-by-step execution:

  1. Start at cell (0,0) containing 'A'
  2. Mark (0,0) as visited and move right to (0,1) containing 'B'
  3. Mark (0,1) as visited and move right to (0,2) containing 'C'
  4. Mark (0,2) as visited and move down to (1,2) containing 'C'
  5. Mark (1,2) as visited and move right to (0,3) containing 'E'
  6. Mark (0,3) as visited and move down to (1,3) containing 'D'
  7. All characters in 'ABCCED' have been found, return true

Hints

Hint 1
Try using backtracking to explore all possible paths from each starting cell.
Hint 2
Make sure to mark visited cells to avoid using the same cell multiple times.
Hint 3
Consider early termination if the current path cannot lead to the target word.

Video Tutorial

Video tutorials can be a great way to understand algorithms visually

Visualization

Visualize the backtracking process on the grid as it searches for the word.

Key visualization elements:

  • current cell
  • visited cells
  • path

Implementation Notes

This problem tests understanding of backtracking and depth-first search in a 2D grid. The key insight is to explore all possible paths while ensuring each cell is used only once.