
Problem
Solution
Submissions
Word Search in a 2D Board
Certification: Intermediate Level
Accuracy: 100%
Submissions: 1
Points: 10
Write a JavaScript program to search for a word in a 2D board of characters. Given a 2D board and a word, find if the 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 in a single word.
Example 1
- Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
- Output: true
- Explanation:
- Start search from each cell that matches first character 'A'.
- Found 'A' at position (0,0), start DFS from here.
- From (0,0), move right to (0,1) for 'B', then (0,2) for 'C'.
- From (0,2), move down to (1,2) for 'C', then (2,2) for 'E'.
- From (2,2), move right to (2,3) for 'D', word "ABCCED" found.
- Start search from each cell that matches first character 'A'.
Example 2
- Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
- Output: true
- Explanation:
- Start search from each cell that matches first character 'S'.
- Found 'S' at position (1,0), start DFS from here.
- From (1,0), no valid path for "SEE".
- Found 'S' at position (1,3), start DFS from here.
- From (1,3), move down to (2,3) for 'E', then left to (2,2) for 'E', word "SEE" found.
- Start search from each cell that matches first character 'S'.
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 word length
- Space Complexity: O(L) for 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 backtracking with DFS to explore all possible paths
- Start the search from every cell that matches the first character of the word
- For each starting position, use DFS to check if the word can be formed
- Mark visited cells during DFS and unmark them when backtracking
- Check all four directions (up, down, left, right) from current cell
- Return true as soon as a valid path is found