Learn Code
Depth-First Search
Greedy Algorithms
Backtracking
Word Search
medium
DESCRIPTION (credit Leetcode.com)
Given an m x n grid of characters board and a string word, return true if 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.
Example 1:
Input:
Output:
Example 2:
Input:
Output:
Explanation
Depth-First Search Function
Keeping Track of Visited Cells
Solution
from typing import Listclass Solution:def exist(self, board: List[List[str]], word: str) -> bool:rows, cols = len(board), len(board[0])def dfs(r, c, index):if index == len(word):return Trueif r < 0 or c < 0 or r >= rows or c >= cols or board[r][c] != word[index]:return Falsetemp = board[r][c]board[r][c] = "#"found = (dfs(r+1, c, index+1) ordfs(r-1, c, index+1) ordfs(r, c+1, index+1) ordfs(r, c-1, index+1))board[r][c] = tempreturn found# initialize depth-first search from# each of the cells that have the same first# letter as wordfor row in range(rows):for col in range(cols):if board[row][col] == word[0]:if dfs(row, col, 0):return Truereturn False
Test Your Knowledge
Login to take the complexity quiz and track your progress
Complexity Analysis
Time Complexity: O(m * n * 4^L) where m
and n
are the dimensions of the grid and L
is the length of the word. We iterate over each cell once (m * n
), and for each cell, we call the dfs
function which makes 4 recursive calls with a max depth of L
, giving us O(4^L)
per cell.
Space Complexity: O(L) where L
is the length of the word. We need to account for the space on the recursive call stack, which can be L
calls deep in the worst case.
Login to track your progress
Your account is free and you can post anonymously if you choose.