注意:本文搜索graph或者tree的方法不是严格的DFS遍历顺序,只是为了DFS的方式搜索所有的可行解。
对于严格DFS非递归遍历的问题,请参考另外一篇文章:
http://blog.csdn.net/starmsg/article/details/39207445
------------------------------
Search solution using dfs while recording the current paths from the root to the current node.
use two stacks, one to simulate the recursion and another for recording the current path.
Code template:
reference: https://community.oracle.com/thread/1662786?start=0&tstart=0
public void seach(int x, int y) {
Stack currentPath = new Stack(); // added
Stack s = new Stack();
s.push(new Pair(x, y));
while (!s.isEmpty()) {
Pair p = (Pair) s.peek(); // changed from pop to peek
visited[p] = true;
currentPath.push(p); // added
if (cell[p] contains search data) // added
break;
for each cell adjacent to p {
if (can move to cell AND cell is not visited)
s.push(new Pair(unvisitedCell.x, unvisitedCell.y));
}
while (!s.isEmpty() && s.peek() == currentPath.peek()) { // added
s.pop();
currentPath.pop();
}
}
}
注意:如果每次可以push相同的元素入栈,见(Combination Sum),则无法通过
s.peek() == currentPath.peek()
区分是否有新的元素push到stack中,此时可以在path中记录stack top的index而非实际的元素,来标记是否有新的元素push。
新的判断条件变成了
(stack.size()-1) == path.back()
参考:http://blog.csdn.net/starmsg/article/details/23112597
For preorder traversal, visit element when pushing it into the stack.
For postorder traversal, visit element when poping it from the stack.
Related Leetcode Questions (more to be appended, all dfs problems)
1. N-Queens
2. Combination Sum
4.
Path Sum
5. Path Sum II
6. Binary Tree Maximum Path Sum
7. Sum Root to Leaf Numbers
Specifically, for binary tree problems(4,5,6,7), besides the above method for path recording, we can have another post-order based
path recording method. Please refer the article:
Binary Tree DFS遍历专题 http://blog.csdn.net/starmsg/article/details/39030379