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.uiFor example, Given board =code
[ ['A','B','C','E']
['S','F','C','S'],
['A','D','E','E'] ]遞歸
word = "ABCCED", -> returns true, word = "SEE", -> returns true, word = "ABCB", -> returns false.字符串
思路:使用dfs. 先在矩陣中找到word0],若找到,就執行helper函數繼續查找。遞歸結束條件是 index == word.length(); 若是是超過邊界或者board[i != word.charAt(index) 就return false。 爲防止same letter cell may be used more than once, 要標記已經訪問過的letter爲 #. 每次遞歸結束之後還要還原以防影響下一次。io
時間複雜度: mn4^(k-1). 也就是mn4^k.
m X n is board size, k is word size.
(腦補題目爲從一個字符矩陣中搜索某個字符串是否存在,能夠向四個方向延伸。那麼dfs和bfs的時間複雜度是指數級別的,大概是4的字符串長度次方,由於每次均可能走四個方向(實際上比這個低,由於不必定四個方向均可以走,也可能走過的地方不能走,可是給出最壞狀況就能夠了))
空間複雜度: recuision最深是k層,recursive部分空間複雜度應該是O(k)class
public class Solution { public boolean exist(char[][] board, String word) { for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { if (board[i][j] == word.charAt(0)) { if (helper(i, j, 0, word,board) == true) { return true; } } } } return false; } private boolean helper(int i, int j, int index, String word, char[][] board) { if (index == word.length()) { return true; } if (i < 0 || j < 0 || i >= board.length || j >= board[0].length || board[i][j] != word.charAt(index)) { return false; } char tmp = board[i][j]; board[i][j] = '#'; boolean rst = helper(i + 1, j, index + 1, word, board) || helper(i, j + 1, index + 1, word, board) || helper(i, j - 1, index + 1, word, board) || helper(i - 1, j, index + 1, word, board); board[i][j] = tmp; return rst; } }