題目
給定一個二維網格和一個單詞,找出該單詞是否存在於網格中。
單詞必須按照字母順序,通過相鄰的單元格內的字母構成,其中“相鄰”單元格是那些水平相鄰或垂直相鄰的單元格。同一個單元格內的字母不允許被重複使用。
示例:
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
給定 word = "ABCCED", 返回 true
給定 word = "SEE", 返回 true
給定 word = "ABCB", 返回 false
提示:
board
和word
中只包含大寫和小寫英文字母。1 <= board.length <= 200
1 <= board[i].length <= 200
1 <= word.length <= 10^3
解題思路
詳細思路請參考 面試題12. 矩陣中的路徑
代碼
class Solution {
public boolean exist(char[][] board, String word) {
int m = board.length;
int n = board[0].length;
boolean[][] isVisited = new boolean[m][n];
char[] chs = word.toCharArray();
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(board[i][j] == chs[0]){
if(dfs(board, i, j, isVisited, chs, 0)){
return true;
}
}
}
}
return false;
}
private boolean dfs(char[][] board, int i, int j, boolean[][] isVisited, char[] chs, int step){
if(step == chs.length){
return true;
}
if(i<0 || i>= board.length || j<0 || j>= board[0].length || isVisited[i][j] || board[i][j] != chs[step]){
return false;
}
isVisited[i][j] = true;
int[][] direction = {{-1, 0}, {0, -1}, {0, 1}, {1, 0}};
for(int k=0; k<4; k++){
if(dfs(board, i+direction[k][0], j+direction[k][1], isVisited, chs, step+1)){
return true;
}
}
isVisited[i][j] = false;
return false;
}
}