79. Word Search
程序员文章站
2022-07-14 17:34:03
...
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.
一刷
题解:
DFS+backtracking
DFS的深度是单词长度L, DFS branching factor是矩阵元素数m x n,所以时间复杂度是(mn)^L
Time Complexity - O((mn)^L), Space Complexity - O(mn)
public class Solution {
public boolean exist(char[][] board, String word) {
if (board == null || word == null || board.length == 0) return false;
int rowNum = board.length, colNum = board[0].length;
boolean[][] visited = new boolean[rowNum][colNum];
for (int i = 0; i < rowNum; i++) {
for (int j = 0; j < colNum; j++) {
if (exist(board, visited, word, i, j, 0)) return true;
}
}
return false;
}
private boolean exist(char[][] board, boolean[][] visited, String word, int i, int j, int pos) {
if (pos == word.length()) return true;
if (i < 0 || j < 0 || i > board.length - 1 || j > board[0].length - 1) return false;
if (visited[i][j] || board[i][j] != word.charAt(pos)) return false;
visited[i][j] = true;
if (exist(board, visited, word, i - 1, j, pos + 1)
|| exist(board, visited, word, i + 1, j, pos + 1)
|| exist(board, visited, word, i, j - 1, pos + 1)
|| exist(board, visited, word, i, j + 1, pos + 1)) return true;
visited[i][j] = false;
return false;
}
}
二刷:
二刷时犯了一个很明显的错误,那就是没有排除掉那些意见被访问过的position
public class Solution {
public boolean exist(char[][] board, String word) {
if(board == null || board.length == 0) return false;
boolean[][] visited = new boolean[board.length][board[0].length];
for(int i=0; i<board.length; i++){
for(int j=0; j<board[0].length; j++){
if(dfs(board, word, i, j, 0, visited)) return true;
}
}
return false;
}
private boolean dfs(char[][] board, String word, int i, int j, int index, boolean[][] visited){
if(index == word.length()) return true;
if(i<0 || i>=board.length || j<0 || j>=board[0].length) return false;
if(board[i][j]!= word.charAt(index) || visited[i][j]) return false;
visited[i][j] = true;
if(dfs(board, word, i+1, j, index+1, visited) || dfs(board, word, i, j+1, index+1, visited)
||dfs(board, word, i-1, j, index+1, visited)
|| dfs(board, word, i, j-1, index+1, visited)) return true;
else{
visited[i][j] = false;
return false;
}
}
}
转载于:https://www.jianshu.com/p/290b9c433f67
上一篇: Leetcode 15.三数之和题解
下一篇: 编码问题