79.word-search-en

Problem

https://leetcode.com/problems/word-search/

Problem Description

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 cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

Example:

board =
[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.

Solution

This problem does not give start position, or direction restriction, so 1. Scan board, find starting position with matching word first letter 2. From starting position, DFS (4 (up, down, left, right 4 directions) match word's rest letters 3. For each visited letter, mark it as visited, here use board[i][j] = '*' to represent visited. 4. If one direction cannot continue, backtracking, mark start position unvisited, mark board[i][j] = word[start] 5. If found any matching, terminate 6. Otherwise, no matching found, return false.

For example:

board, word:SEE as below pic:

word search 1

Staring position(1,0), check whether adjacent cells match word next letter E.

Didn't find matching from starting position, so

New starting position(1,3),check whether adjacent cells match word next letter E.

word search 4

Start position(0,3), DFS,check whether adjacent cells match word next letter E

Start from position(0,3)not matching word,

word search 6

Found match with word, return True. word search 7

Complexity Analysis

  • Time Complexity: O(m*n) - m is number of board rows, n is number of board columns

  • Space Complexity: O(1) - no extra space

Note:if use Set or boolean[][] mark position visited,need extra space O(m*n).

Key Points

  • Scan board, find start position which match word first letter, DFS

  • Remember visited letter

  • Backtracking if not found matching

Code (Java/Javascript/Python3)

Java Code

Python3 Code

Javascript Code from @lucifer

References

Last updated

Was this helpful?