劍指offer:矩陣中的路徑(Java、Python)
阿新 • • 發佈:2019-02-17
補上自己上週做的題,上週忘記寫了,希望不會忘記。。。
決定從今往後先用Java解題了,Python實現有的時候太輕鬆,輕鬆的不真實;而且Python無論是對資料結構的封裝還是操作,來的太容易;作為一個主體語言依然用Java的我而言,還是先精通Java吧~;這道題是牛客網-劍指offer中倒數第二道題,同時附上Java和Python的解法。可能是用Python太多,感覺思路有點偏Python的思路…
題目描述
請設計一個函式,用來判斷在一個矩陣中是否存在一條包含某字串所有字元的路徑。路徑可以從矩陣中的任意一個格子開始,每一步可以在矩陣中向左,向右,向上,向下移動一個格子。如果一條路徑經過了矩陣中的某一個格子,則該路徑不能再進入該格子。 例如 a b c e s f c s a d e e 矩陣中包含一條字串”bcced”的路徑,但是矩陣中不包含”abcb”路徑,因為字串的第一個字元b佔據了矩陣中的第一行第二個格子之後,路徑不能再次進入該格子。
解題思路
上述例子所組成的矩陣樣式:
a b c e
s f c s
a d e e
分別以陣列中的每個元素為起點,判斷從該起點開始,是否包含給定的字串的路徑。方法採用遞迴即可。不難;我看一些是說用回溯法,和遞迴一個樣。
Java版
自己在實現的過程中需要測試程式碼,因為main函式是靜態的,因此實現的方法也就是靜態的了;懶得刪,就一起放上來了:
import java.util.Arrays;
public class MatrixPath {
public static boolean hasPath(char[] matrix, int rows, int cols, char[] str){
boolean[] assistMatrix = new boolean[rows*cols];
Arrays.fill(assistMatrix, true);
for(int i=0; i<rows; i++) {
for(int j=0; j<cols; j++) {
if(hasPathAtAStartPoint(matrix, rows, cols, str, i, j, assistMatrix)) {
return true;
}
}
}
return false;
}
public static boolean hasPathAtAStartPoint(char[] matrix, int rows, int cols, char[] str, int row, int col, boolean[] assistMatrix) {
if(str.length <= 0) {
return true;
}
int index = row*cols + col;
if(row<0 || row>=rows ||col<0 ||col>=cols || assistMatrix[index]==false || matrix[index] != str[0]) {
return false;
}
assistMatrix[index] = false;
char[] strRest = Arrays.copyOfRange(str, 1, str.length);
if(hasPathAtAStartPoint(matrix,rows,cols,strRest,row+1,col,assistMatrix)||
hasPathAtAStartPoint(matrix,rows,cols,strRest,row-1,col,assistMatrix)||
hasPathAtAStartPoint(matrix,rows,cols,strRest,row,col+1,assistMatrix)||
hasPathAtAStartPoint(matrix,rows,cols,strRest,row,col-1,assistMatrix)) {
return true;
}
assistMatrix[index] = true;
return false;
}
// A B C E
// S F C S
// A D E F
public static void main(String[] args) {
char[] matrix = {'A','B','C','E','S','F','C','S','A','D','E','F'};
char[] str = {'A','B','C','C','E','D'};
System.out.println(hasPath(matrix,3,4,str));
}
}
Python版
class Solution:
def hasPath(self, matrix, rows, cols, path):
assistMatrix = [True]*rows*cols
for i in range(rows):
for j in range(cols):
if(self.hasPathAtAStartPoint(matrix,rows,cols, i, j, path, assistMatrix)):
return True
return False
def hasPathAtAStartPoint(self, matrix, rows, cols, i, j, path, assistMatrix):
if not path:
return True
index = i*cols+j
if i<0 or i>=rows or j<0 or j>=cols or matrix[index]!=path[0] or assistMatrix[index]==False:
return False
assistMatrix[index] = False
if(self.hasPathAtAStartPoint(matrix,rows,cols,i+1,j,path[1:],assistMatrix) or
self.hasPathAtAStartPoint(matrix,rows,cols,i-1,j,path[1:],assistMatrix) or
self.hasPathAtAStartPoint(matrix,rows,cols,i,j-1,path[1:],assistMatrix) or
self.hasPathAtAStartPoint(matrix,rows,cols,i,j+1,path[1:],assistMatrix)):
return True
assistMatrix[index] = True
return False