⌘K
Flycodx

Word Search

Word Search

MediumGraphs25% accepted

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

3 4 A B C E S F C S A D E E ABCCED

Output

YES
  • •1 ≤ m, n ≤ 6, 1 ≤ word length ≤ 15, grid cells are uppercase letters
solution.py
Loading editor...
Test 1
Test 2
Test 3

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
Auto Save OnLn 1, Col 1Spaces: 4UTF-8LFPython 3