Leetcode 79: Word Search

grid47
grid47
Exploring patterns and algorithms
Oct 30, 2024 6 min read

A glowing word appearing in a soft matrix of letters, slowly highlighting itself.
Solution to LeetCode 79: Word Search Problem

You are given a 2D grid board containing characters and a string word. The task is to determine whether the given word can be formed by starting at any cell in the grid and moving to adjacent cells, which are horizontally or vertically neighboring. The same cell cannot be reused in forming the word.
Problem
Approach
Steps
Complexity
Input: The input consists of a 2D grid `board` of characters and a string `word`.
Example: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Constraints:
• 1 <= m, n <= 6
• 1 <= word.length <= 15
• board and word consist of only uppercase and lowercase English letters.
Output: Return `true` if the word exists in the grid, otherwise return `false`.
Example: true
Constraints:
• The solution should return true if the word can be formed from the grid, and false otherwise.
Goal: To check if a word can be formed by navigating the grid's adjacent cells.
Steps:
• Iterate over each cell in the grid.
• For each cell, perform a Depth-First Search (DFS) to explore all possible paths that form the word, marking cells as visited.
• If a complete path that forms the word is found, return true; otherwise, continue the search.
Goal: The problem constraints ensure that the grid size is small and the word length is manageable.
Steps:
• 1 <= m, n <= 6
• 1 <= word.length <= 15
Assumptions:
• The grid and word consist only of valid English alphabetic characters.
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Explanation: Starting at the top-left corner, the word 'ABCCED' can be formed by moving through adjacent cells.

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
Explanation: The word 'SEE' can be formed by starting from the bottom-left corner.

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
Explanation: The word 'ABCB' cannot be formed because the letter 'B' would need to be reused.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus