import java.util.Stack;
import java.util.Vector;
public class E05 {
public static void main(String[] args) {
String str = "ABCEHJIGSFCSLOPQADEEMNOEADIDEJFMVCEIFGGS";
char[] matrix = str.toCharArray();
String str2 = "ABCCEIDESEHJONOF";
char[] c = str2.toCharArray();
System.out.println(new Solution5().hasPath(matrix, 5, 8, c));
}
}
class Solution5 {
public boolean hasPath(char[] matrix, int rows, int cols, char[] str) {
if(matrix.length<=0||rows<0||cols<0||str.length<=0){
return false;
} //rows从0开始
Vector<Character> Map=new Vector<>();
for (Character character : matrix) {
Map.add(character);
}
Stack<Integer> Path=new Stack<>();
if(Map.contains(str[0])){
int i=0;
for (Character character : Map) {
if(character==str[0]){
Path.push(i);
}
i++;
}
}
else return false;
boolean res=detect(Path,Map,rows,cols,str,0);
return res;
}
// 从起始位置开始判断是否有路径
public boolean detect(Stack<Integer> Path,Vector<Character> Map,int rows,int cols,char[] str,int i) {
if(Path.isEmpty()){
return false;
}
if(i>=str.length-1){
return true;
}
int index=Path.peek();
if(judge(Map,index,str,i)){ //0标记已经检验过
Map.set(index, '0');
}
boolean a,b,c,d;
if(a=judge(Map, index+cols, str, i+1)){ //探测四周
Path.push(index+cols);
}
if(b=judge(Map, index-cols, str, i+1)){
Path.push(index-cols);
}
if(c=judge(Map, index+1, str, i+1)){
Path.push(index+1);
}
if(d=judge(Map, index-1, str, i+1)){
Path.push(index-1);
}
// 判断当前点是否可以前进,若不能前进则后退,直到可以前进为止
if(!(a||b||c||d)){
Path.pop();
if(Map.get(Path.peek())=='0'){
return false;
}
i--;
}
// 遍历完str后返回是否探测到路径
return detect(Path, Map, rows, cols, str, i+1);
}
public boolean judge(Vector<Character> Map,int index,char[] str,int i) {
if(index<0||index>=Map.size()){
return false;
}
return Map.get(index)==str[i];
}
}
剑指Offer-矩阵中的路径
最新推荐文章于 2021-07-14 15:00:02 发布