Leetcode#79. Word Search
Problem
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:
!https://assets.leetcode.com/uploads/2020/11/04/word2.jpg
1 | Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED" |
Example 2:
!https://assets.leetcode.com/uploads/2020/11/04/word-1.jpg
1 | Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE" |
Example 3:
!https://assets.leetcode.com/uploads/2020/10/15/word3.jpg
1 | Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB" |
Constraints:
m == board.length
n = board[i].length
1 <= m, n <= 6
1 <= word.length <= 15
board
andword
consists of only lowercase and uppercase English letters.
Follow up: Could you use search pruning to make your solution faster with a larger board
?
Solve
先全部搜索,當找到第一個字母時,再開始跑 DFS
DFS的概念,
1.判斷是否找到了,如果找到了,就回傳True
2.判斷是否超出邊界,或是word的第一個字母不等於board[i][j]時,代表找不到,回傳False
3.把board[i][j]標記為 #,代表已經走過了
4.往上下左右四個方向走,並且word往後一個字母
5.把board[i][j]還原
6.回傳結果
backtracking 的觀念,當發現走不下去時,就把標記還原,然後往另一個方向走
老鼠走迷宮的概念
解法
1 | class Solution: |
Time complexity: O(m*n * 4^L) mn is the size of the board and L is the length of the word
Space complexity: O(L) where L is the length of the word