Word Search
Word Search
Given an m×n character grid and a word, determine if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cells (horizontally or vertically). The same cell may not be used more than once. Input format: - First line: two integers m (rows) and n (cols) - Next m lines: each containing n characters separated by spaces - Last line: the word to search for Output: YES if the word exists in the grid, NO otherwise. Example: 4×4 grid and word "ABCCED" → YES
Approach
Backtracking DFS: for each cell matching word[0], run DFS trying to match word[1], word[2], ... in the 4 adjacent directions. Mark cells as visited during recursion (e.g., replace with '#') and restore them on backtrack.
Input
Output
- •
1 ≤ m, n ≤ 6, 1 ≤ word length ≤ 15, grid cells are uppercase letters
More Graphs problems
Browse all coding problems →Press Run to test your custom input, or Submit to judge against all test cases.
Sign in to continue
Create a free account to run code, submit solutions and track progress.
- Free forever — no credit card
- 10+ languages with live execution
- Points, streaks & leaderboards