Tutorialspoint
Problem
Solution
Submissions

Word Search Problem

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C# program to solve the Word Search problem. 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
  • Explanation:
    • The word "ABCCED" can be found by starting at the top-left A and following these paths:
    • 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 found by starting at the middle S and following this path:
    • S → E → E
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
  • Time Complexity: O(m * n * 4^L) where L is the length of word
  • Space Complexity: O(L) for the recursion stack
AlgorithmsBacktracking IBM
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use depth-first search (DFS) with backtracking
  • Start the search from every cell in the grid
  • Mark visited cells to avoid using the same cell multiple times
  • Explore in all four directions (up, down, left, right) for each cell
  • Backtrack by unmarking cells when a path doesn't lead to a solution

Steps to solve by this approach:

 Step 1: Iterate through each cell in the grid as a potential starting point.
 Step 2: For each cell that matches the first character of the word, start a DFS search.
 Step 3: In the DFS function, check if we've found the complete word (base case for success).
 Step 4: Check boundary conditions and whether the current cell matches the expected character.
 Step 5: Mark the current cell as visited to avoid using it again in the same path.
 Step 6: Recursively explore all four adjacent cells (up, down, left, right) to continue the search.
 Step 7: Backtrack by restoring the cell's original value after exploration.

Submitted Code :