今天继续刷leetcode,第79题,求单词路径;
分析:
采用dfs的方式,上下左右遍历,找到路径就返回true;
碰到一下三种情况,就返回false:
(1)超过边界;
(2)访问过;
(3)不等于目标值;
附上c++代码:
class Solution {
int d[4][2]={{-1,0},{0,1},{1,0},{0,-1}};
int m,n;
vector<vector<bool>> visited;
bool inArea(int x,int y)
{
bool res=(x>=0 && x<m &&y>=0 && y<n);
return res;
}
//从board[startx][starty]开始寻找,寻找word[index]
bool find(vector<vector<char>>& board, string& word,int index,int startx, int starty)
{
if(index == word.size()-1)
return board[startx][starty] == word[index];
if(board[startx][starty] == word[index])
{
visited[startx][starty]=true;
//向4个方向寻找
for(int i=0;i<4;i++)
{
int newx=startx+d[i][0];
int newy=starty+d[i][1];
if(inArea(newx,newy) && !visited[newx][newy])
{
bool re = find(board,word,index+1,newx,newy);
if(re == true)
return true;
}
}
//四个方向都没找到,退回
visited[startx][starty]=false;
}
return false;
}
public:
bool exist(vector<vector<char>>& board, string word) {
m=board.size();
if(m == 0)
return false;
n=board[0].size();
visited = vector<vector<bool>>(m, vector<bool>(n,false));
for(int i=0;i<board.size();i++)
for(int j=0;j<board[i].size();j++)
{
bool res= find(board,word,0,i,j);
if(res == true)
return true;
}
return false;
}
};
附上python代码:
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
if not word or not board:
return False
m, n= len(board), len(board[0])
if m==0 or n==0:
return False;
visited = [[False]*n for _ in range(m)]
for i in range(m):
for j in range(n):
if self._searchWord(board, word, 0, i, j, visited):
return True
return False
def _searchWord(self, board, word, index, x, y, visited):
m, n= len(board), len(board[0])
def inArea(x, y):
return 0 <= x < m and 0 <= y < n
d = [(-1, 0), (0, 1), (1, 0), (0, -1)]
if index + 1 == len(word):
return board[x][y] == word[index]
if board[x][y] == word[index]:
visited[x][y] = True
for i in range(4):
x_ = x + d[i][0]
y_ = y + d[i][1]
if inArea(x_, y_) and not visited[x_][y_] and \
self._searchWord(board, word, index + 1, x_, y_, visited):
return True
visited[x][y] = False
return False