
Problem
Solution
Submissions
Word Search in a 2D Board
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a C program to determine if a given word exists in a 2D board of characters. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same cell cannot 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:
- Step 1: Start at board[0][0] = 'A', which matches the first character of "ABCCED".
- Step 2: Move right to board[0][1] = 'B', which matches the second character.
- Step 3: Move right to board[0][2] = 'C', which matches the third character.
- Step 4: Move down to board[1][2] = 'C', which matches the fourth character.
- Step 5: Move down to board[2][2] = 'E', which matches the fifth character.
- Step 6: Move left to board[2][1] = 'D', which matches the last character.
- Step 7: The word "ABCCED" is found in the board.
Example 2
- Input:
- board = [ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ]
- word = "SEE"
- Output: true
- Explanation:
- Step 1: One possible path starts at board[1][0] = 'S'.
- Step 2: Move right to board[1][3] = 'S' (after trying other paths that don't work).
- Step 3: Move up to board[0][3] = 'E'.
- Step 4: Move down to board[2][3] = 'E'.
- Step 5: The word "SEE" is found in the board.
Constraints
- m == board.length
- n == board[i].length
- 1 <= m, n <= 6
- 1 <= word.length <= 15
- board and word consist of only uppercase English letters
- Time Complexity: O(m*n*4^L), where L is the length of the word
- Space Complexity: O(m*n) for the visited array and recursion stack
Editorial
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. |
Solution Hints
- Use a depth-first search (DFS) approach to explore all possible paths.
- For each cell in the board, try to match the first character of the word.
- If the first character matches, recursively search for the remaining characters.
- Keep track of visited cells to avoid using the same cell multiple times.
- Use backtracking: if a path doesn't lead to a solution, backtrack and try other paths.