答题中很多都是采用递归方式实现,思路直接,简单。但是如果采用非递归实现方式实现,该怎么实现呢?下面就解释一下如何通过非递归方式实现。
路径寻找过程中,整体的节点构成了一个树形结构,树形结构通过根节点互相连接。
1.定义一个marks数组标记当前的节点是否访问过,被访问过的节点,我们把他们叫做关键节点,整个路径通过关键节点连接。
2.定义两个栈结构,本例中使用两个LinkedList rowStack和colStack,分别记录行坐标和列坐标。
整体逻辑如下:
- 如果marks数组中标记有被访问过,说明此节点是关键节点。再次访问关键节点说明路径已经无法走通,需要pop关键节点。
- 如果未被访问过: 一种情况是,此节点正好是要找的值,这个时候需要把此节点定义为关键节点,然后把此关键节点的临接节点存到rowStack和colStack。
另外一种情况是,此节点不是要找的值,这个时候把此节点pop即可,路径无效。 - 重复执行1和2,直到rowStack或者colStack为空。
import java.util.Stack;
import java.util.Arrays;
import java.util.LinkedList;
public class Solution{
public static boolean hasPath(char[] matrix, int rows, int cols, char[] str)
{
int[] marks = new int[rows*cols];
for (int row = 0; row < rows; ++row) {
for (int col = 0; col < cols; ++col) {
Arrays.setAll(marks, i->0);
if(isHasPath( matrix, marks, rows, cols, row, col, str)) {
return true;
}
}
}
return false;
}
public static boolean isHasPath(char[] matrix,int[] marks, int rows, int cols, int row, int col, char[] str)
{
int currentIndex = 0;
int count = 0;
// LinkedList<Integer> visitedStack = new LinkedList<>();
LinkedList<Integer> rowStack = new LinkedList<>();
LinkedList<Integer> colStack = new LinkedList<>();
rowStack.push(row);
colStack.push(col);
int[][] newIndexes = new int[][]{
{1, 0}, {-1, 0}, {0, 1}, {0, -1}
};
while (!rowStack.isEmpty()){
count ++;
int topX = colStack.peek();
int topY = rowStack.peek();
int topIndex = topY*cols + topX;
if(currentIndex == str.length) {
return true;
}
if(marks[topIndex] ==0) {
if(matrix[topIndex]==str[currentIndex]) {
for(int j =0; j <newIndexes.length; ++ j){
int newX = topX + newIndexes[j][0];
int newY = topY + newIndexes[j][1];
if(newX>=0&&newX<cols && newY>=0 && newY<rows){
int newIndex = newY*cols+newX;
if(marks[newIndex] !=1){//not visited.
colStack.push(newX);
rowStack.push(newY);
}
}
}
marks[topIndex] = 1;
//visitedStack.push(topIndex);
currentIndex ++;
}else {
colStack.pop();
rowStack.pop();
}
} else {
//back to the visited
marks[topIndex] = 0;
colStack.pop();
rowStack.pop();
// if(visitedStack.size()>0)
// visitedStack.pop();
currentIndex --;
}
}
String strlog = String.format("%d x %d: %d", cols, rows, count);
System.out.println(strlog);
return false;
}
}

京公网安备 11010502036488号