githubEdit

27. Word Search

βœ… GFG solution to the Word Search problem: find if a word exists in a 2D character matrix using DFS backtracking technique. πŸš€

The problem can be found at the following link: πŸ”— Question Linkarrow-up-right

🧩 Problem Description

You are given a matrix mat[][] of size n*m containing English alphabets and a string word. Check if the word exists on the mat[][] or not. The word can be constructed by using letters from adjacent cells, either horizontally or vertically. The same cell cannot be used more than once.

A valid word path is formed by connecting adjacent cells where each cell can only be visited once during the search for a particular word.

πŸ“˜ Examples

Input:

mat[][] = [['T', 'E', 'E'],
           ['S', 'G', 'K'],
           ['T', 'E', 'L']]
word = "GEEK"

Output: true Explanation:

The letters used to construct "GEEK" are found in the grid.

Input:

mat[][] = [['T', 'E', 'U'],
           ['S', 'G', 'K'],
           ['T', 'E', 'L']]
word = "GEEK"

Output: false Explanation:

The word "GEEK" cannot be formed from the given grid.

Input:

Output: true Explanation:

There are multiple ways to construct the word "AB".

πŸ”’ Constraints

  • $1 \le n, m \le 6$

  • $1 \le \text{word.size()} \le 15$

  • mat and word consists of only lowercase and uppercase English letters.

βœ… My Approach

The optimal approach uses DFS Backtracking to explore all possible paths in the matrix:

DFS Backtracking Algorithm

  1. Initialize Search:

    • Iterate through each cell in the matrix as a potential starting point.

    • When the first character of the word matches a cell, start DFS from that position.

  2. DFS Exploration:

    • Check if current position is valid (within bounds and matches current character).

    • Mark current cell as visited by replacing it with a special character (e.g., '*').

    • Recursively explore all 4 adjacent directions (up, down, left, right).

  3. Backtrack:

    • After exploring all paths from current cell, restore the original character.

    • This allows the cell to be used in other potential word paths.

  4. Base Cases:

    • If we've matched all characters in the word, return true.

    • If current position is invalid or character doesn't match, return false.

  5. Return Result:

    • Return true if any starting position leads to a complete word match.

    • Return false if no valid path is found after checking all positions.

πŸ“ Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(n Γ— m Γ— 4^L), where n and m are matrix dimensions and L is the word length. In worst case, we explore all cells as starting points and from each cell, we explore 4 directions recursively up to word length L.

  • Expected Auxiliary Space Complexity: O(L), where L is the length of the word. This space is used by the recursion stack, which can go as deep as the word length. We don't use any additional data structures apart from the recursion call stack.

πŸ§‘β€πŸ’» Code (C++)

chevron-right⚑ View Alternative Approaches with Code and Analysishashtag

πŸ“Š 2️⃣ Optimized Early Exit with Character Frequency

πŸ’‘ Algorithm Steps:

  1. Build frequency map of characters in board and word before starting the search.

  2. Perform early rejection if word contains characters not present in board or if frequency is insufficient.

  3. Optimize search direction by starting from the less frequent character end.

  4. Use standard DFS backtracking with the optimized starting point.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n Γ— m) for preprocessing + O(n Γ— m Γ— 4^L) for DFS search

  • Auxiliary Space: πŸ’Ύ O(L + K) where L is recursion depth and K is number of unique characters in word

βœ… Why This Approach?

  • Early rejection saves time for impossible cases

  • Character frequency optimization reduces search space

  • Reversing word when needed minimizes starting points to explore

πŸ†š πŸ” Comparison of Approaches

πŸš€ Approach

⏱️ Time Complexity

πŸ’Ύ Space Complexity

βœ… Pros

⚠️ Cons

πŸ”„ DFS Backtracking

🟑 O(nΓ—mΓ—4^L)

🟒 O(L)

πŸš€ Simple and clean

πŸ”§ No early pruning

⚑ Frequency Optimized

🟒 O(nΓ—mΓ—4^L)

🟑 O(L+K)

🎯 Early pruning, fewer searches

πŸ”§ Extra preprocessing overhead

πŸ† Best Choice Recommendation

🎯 Scenario

πŸŽ–οΈ Recommended Approach

πŸ”₯ Performance Rating

πŸ… Short words, small boards

πŸ₯‡ DFS Backtracking

β˜…β˜…β˜…β˜…β˜…

πŸ”§ Large boards with impossible words

πŸ₯ˆ Frequency Optimized

β˜…β˜…β˜…β˜…β˜…

β˜• Code (Java)

🐍 Code (Python)

🧠 Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: πŸ“¬ Any Questions?arrow-up-right. Let's make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


πŸ“Visitor Count

Visitor counter

Last updated