<79> Word Search
Description
Question: 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.
Leetcode link: 79. Word Search
Quick Sum-up:
- Input: a 2D array and a string
- Output: a boolean value indicating whether the string can be assembled by the characters in the array
Idea
For each cell in the array, if the character is the same as the first character of the string, check whether its neighbors contain the following character. Use a 2D array to record whether a cell has been visited. The recursive loop stops when the end of string is reached. => Pass, 76ms
Test cases
Input1 | Input2 | Expected Output |
---|---|---|
board=[ ["A","B","C","E"], ["S","F","C","S"], ["A","D","E","E"] ] |
word="ABCCED" word="SEE" word="ABCB" |
true true false |
board=[] | word="" | false |
board=[[""]] | word="" | false |
board=[[]] | word="ABC" | false |
board=[["A"]] | word="ABC" | fasle |
Solution
1 | /** |