【Java题解】剑指 Offer 12. 矩阵中的路径
一、题目
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一格开始,每一步可以在矩阵中向左、右、上、下移动一格。如果一条路径经过了矩阵的某一格,那么该路径不能再次进入该格子。例如,在下面的3×4的矩阵中包含一条字符串“bfce”的路径(路径中的字母用加粗标出)。
[["a","b","c","e"], ["s","f","c","s"], ["a","d","e","e"]]
但矩阵中不包含字符串“abfb”的路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入这个格子。
示例 1:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]],
word = "ABCCED"
输出:true示例 2:
输入:board = [["a","b"],["c","d"]], word = "abcd"
输出:false
提示:1 <= board.length <= 200
1 <= board[i].length <= 200
二、代码
class Solution {
private int rowl, coll;
private boolean[][] visited;
private int[][] direction;
public boolean exist(char[][] board, String word) {
if(board == null || word == null || board.length == 0 || board[0].length == 0){
return false;
}
rowl = board.length;
coll = board[0].length;
visited = new boolean[rowl][coll];
direction = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
char[] mywords = word.toCharArray();
for(int i = 0; i < rowl; i++){
for(int j = 0; j < coll; j++){
visited[i][j] = false;
}
}
for(int row = 0; row < rowl; row++){
for(int col = 0; col < coll; col++){
boolean res = dfs(board, mywords, row, col, 0);
if(res){
return true;
}
}
}
return false;
}
public boolean dfs(char[][] board, char[] mywords, int row, int col, int index){
if(visited[row][col] || board[row][col] != mywords[index]){
return false;
}
if(index == mywords.length - 1){
return true;
}
visited[row][col] = true;
boolean result = false;
for(int[] dir : direction){
int newr = row + dir[0];
int newc = col + dir[1];
if(newr >= 0 && newr < rowl && newc >= 0 && newc <coll && !visited[newr][newc]){
boolean res2 = dfs(board, mywords, newr, newc, index+1);
if(res2){
return true;
}
}
}
visited[row][col] = false;
return false;
}
}