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.
For example,
Given board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.
一.此题核心是深度优先搜索,深搜的步骤一般是:
1.判断参数的合法性
2.组合路径的所有值,与搜索条件进行判断,如不符合退出,如符合转3
3.标记当前节点已经访问
4.继续深搜
5.还原节点为未访问
二.时间复杂度
最坏情况下,从任何一点出发,需要把所有路径遍历完才能找到符合条件的路径,时间复杂度为O(mn),一共有mn个结点,所以总的时间复杂度是O(m*m*n*n);
三.空间复杂度
深度优先的情况下,对矩阵的搜索可以改成多叉树,树的深度为最长搜索路径,也就是m+n,所以时间复杂度是O(m+n);
四.代码
1 class Solution { 2 public: 3 bool dfs(vector<vector<char>>& board,string& word,int curIndex,int r,int c) 4 { 5 /* 先进行坐标合法性判断 */ 6 if(r<0 || r>=board.size() || c<0 || c>=board[0].size()){ 7 return false; 8 } 9 10 if(curIndex < word.size() && word[curIndex]!=board[r][c]){ 11 return false; 12 } 13 14 /* 先判断当前是否word的最后一个字符,如果是则找到了,直接返回,如果不是继续比较word的后一串是否能再board中找到*/ 16 if((curIndex+1) == word.size()){ 17 return true; 18 } 19 char tmp = board[r][c];//递归结束后还要回复状态 20 board[r][c] = '#'; 21 bool res = dfs(board,word,curIndex+1,r-1,c) || dfs(board,word,curIndex+1,r,c+1)|| 22 dfs(board,word,curIndex+1,r+1,c) || dfs(board,word,curIndex+1,r,c-1); 23 if(res){ 24 return true; 25 } 26 board[r][c] = tmp ; 27 return false; 28 } 29 30 public: 31 bool exist(vector<vector<char>>& board, string word) { 32 if(board.size()<0 || word.size()<0){ 33 return false; 34 } 35 int irepeatTime = board.size(); 36 int jrepeatTime = board[0].size(); 37 for(int i=0;i<irepeatTime;i++){ 38 for(int j=0;j<jrepeatTime;j++){ 39 if(dfs(board,word,0,i,j)){ 40 return true; 41 } 42 } 43 } 44 return false; 45 } 46 };