79. 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.
1 | Example: |
Solution:
- Since the question mentioned there’s only one possible solution, we should use DFS.
- Use pre_check to see if any chac in
word
is not in board - Temporary set
board[i][j]
to other character.
1 | class Solution: |
- use DFS to find whether the word exist
- create a 2D bool array to record used elements in each DFS, the range should be [rowNum][colNum]
- find word with start in each slot[i][j]
In auxiliary function:
First we check pos is equal to word.length(), return true if it’s the same.
Second, if anything is out of range, then return false.
Third, return false if (we already visited this slot) || ([i][j] is different from the word[pos])
1 | class Solution { |
Reference:
https://goo.gl/QLs5yW