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是矩陣元素數(shù)m x n,所以時間復(fù)雜度是(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;
}
}
}