题目:
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.
Example:
board =
[
[‘A’,‘B’,‘C’,‘E’],
[‘S’,‘F’,‘C’,‘S’],
[‘A’,‘D’,‘E’,‘E’]
]
Given word = “ABCCED”, return true.
Given word = “SEE”, return true.
Given word = “ABCB”, return false.
解法1:
DFS
首先在主程序中对矩阵的每个位置都进行深度优先搜索,如果有一个位置可以找到可以与之匹配的字符串则返回true
如果全部遍历完还是无法匹配则返回false
DFS函数:
参数:矩阵board 待匹配的字符串word 矩阵的位置:i和j,匹配的字符串的位置idx,记录是否访问过的数组visited
如果匹配的字符串的位置到达字符串的末尾,说明我们已经匹配成功了,返回true
如果矩阵的位置越界或者这个位置我们之前访问过,即走了回头路,或者当前的矩阵的元素不匹配字符串,我们都返回false
如果当前位置成功匹配字符串的位置,字符串可以往后移一位,而矩阵可以朝四个方向移动,只要有一个方向可以匹配,我们就返回true
递归前,将visited置为true,递归后恢复原状
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
int row = board.size();
if(row == 0) return false;
int col = board[0].size();
if(col == 0) return false;
vector<vector<bool>> visited(row,vector<bool>(col,false));
for(int i = 0; i < row; ++i){
for(int j = 0; j < col; ++j){
if(DFS(board,word,0,i,j,visited)) return true;
}
}
return false;
}
bool DFS(vector<vector<char>>& board, string word,int idx,int i, int j,vector<vector<bool>>& visited) {
if(idx == word.size()) return true;
int row = board.size();
int col = board[0].size();
if(i < 0 || j < 0 || i >= row || j >= col || visited[i][j] || board[i][j] != word[idx]) return false;
visited[i][j] = true;
bool res = DFS(board, word,idx + 1,i - 1, j,visited) ||
DFS(board, word,idx + 1,i + 1, j,visited) ||
DFS(board, word,idx + 1,i, j - 1,visited) ||
DFS(board, word,idx + 1,i, j + 1,visited);
visited[i][j] = false;
return res;
}
};
class Solution {
public boolean exist(char[][] board, String word) {
int row = board.length;
if(row == 0) return false;
int col = board[0].length;
if(col == 0) return false;
boolean[][] visited = new boolean[row][col];
for(int i = 0; i < row; ++i){
for(int j = 0; j < col; ++j){
if(DFS(board,word,0,i,j,visited) == true) return true;
}
}
return false;
}
boolean DFS(char[][] board, String word,int idx,int i, int j,boolean[][] visited) {
if(idx == word.length()) return true;
int row = board.length;
int col = board[0].length;
if(i < 0 || j < 0 || i >= row || j >= col || visited[i][j] == true || board[i][j] != word.charAt(idx)) return false;
visited[i][j] = true;
boolean res = DFS(board, word,idx + 1,i - 1, j,visited) ||
DFS(board, word,idx + 1,i + 1, j,visited) ||
DFS(board, word,idx + 1,i, j - 1,visited) ||
DFS(board, word,idx + 1,i, j + 1,visited);
visited[i][j] = false;
return res;
}
}
python:
- 可以用word[1:]的语法表示向后移
- board[i][j] != word[0],python3 可以用board[i][j] is not word[0],暂时不知道原因
class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
row = len(board)
if row == 0: return False
col = len(board[0])
if col == 0: return False
visited = [[False for i in xrange(col)] for j in xrange(row)]
for i in xrange(row):
for j in xrange(col):
if self.dfs(i, j, board, word,visited):
return True
return False
def dfs(self, i, j, board, word,visited):
if not word:
return True
#print id(board[i][j]),id(word[0])
if i < 0 or j < 0 or i >= len(board) or j >= len(board[0]) or visited[i][j] or board[i][j] != word[0]:
return False
visited[i][j] = True
exist = self.dfs(i-1,j,board,word[1:],visited) or self.dfs(i,j-1,board,word[1:],visited) or\
self.dfs(i,j+1,board,word[1:],visited) or self.dfs(i+1,j,board,word[1:],visited)
visited[i][j] = False
return exist
解法2:
DFS 减少空间复杂度
我们也可以不用visited,而直接用矩阵直接当visited,如果访问过这个元素,给它赋一个不会出现的元素,如‘ ’,这样的话如果走回头路的话board[i][j] != word[idx]条件一定不会成立,赋值之前首先要首先记录一下该值,在递归完成后恢复
c++:
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
int row = board.size();
if(row == 0) return false;
int col = board[0].size();
if(col == 0) return false;
//vector<vector<bool>> visited(row,vector<bool>(col,false));
for(int i = 0; i < row; ++i){
for(int j = 0; j < col; ++j){
if(DFS(board,word,0,i,j)) return true;
}
}
return false;
}
bool DFS(vector<vector<char>>& board, string word,int idx,int i, int j) {
if(idx == word.size()) return true;
int row = board.size();
int col = board[0].size();
if(i < 0 || j < 0 || i >= row || j >= col || board[i][j] != word[idx]) return false;
char temp = board[i][j];
board[i][j] = ' ';
bool res = DFS(board, word,idx + 1,i - 1, j) ||
DFS(board, word,idx + 1,i + 1, j) ||
DFS(board, word,idx + 1,i, j - 1) ||
DFS(board, word,idx + 1,i, j + 1);
board[i][j] = temp;
return res;
}
};
java:
class Solution {
public boolean exist(char[][] board, String word) {
int row = board.length;
if(row == 0) return false;
int col = board[0].length;
if(col == 0) return false;
//boolean[][] visited = new boolean[row][col];
for(int i = 0; i < row; ++i){
for(int j = 0; j < col; ++j){
if(DFS(board,word,0,i,j) == true) return true;
}
}
return false;
}
boolean DFS(char[][] board, String word,int idx,int i, int j) {
if(idx == word.length()) return true;
int row = board.length;
int col = board[0].length;
if(i < 0 || j < 0 || i >= row || j >= col || board[i][j] != word.charAt(idx)) return false;
char temp = board[i][j];
board[i][j] = ' ';
boolean res = DFS(board, word,idx + 1,i - 1, j) ||
DFS(board, word,idx + 1,i + 1, j) ||
DFS(board, word,idx + 1,i, j - 1) ||
DFS(board, word,idx + 1,i, j + 1);
board[i][j] = temp;
return res;
}
}
python:
class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
row = len(board)
if row == 0: return False
col = len(board[0])
if col == 0: return False
print row,col
for i in xrange(row):
for j in xrange(col):
if self.dfs(i, j, board, word):
return True
return False
def dfs(self, i, j, board, word):
print word
if not word:
return True
if i < 0 or j < 0 or i >= len(board) or j >= len(board[0]) or board[i][j] != word[0]:
return False
temp = board[i][j]
board[i][j] = ''
print "hahhahhha"
exist = self.dfs(i-1,j,board,word[1:]) or self.dfs(i,j-1,board,word[1:]) or \
self.dfs(i,j+1,board,word[1:]) or self.dfs(i+1,j,board,word[1:])
board[i][j] = temp
print exist
return exist