DFS Search with Path Recording

22 篇文章 0 订阅
3 篇文章 0 订阅

注意:本文搜索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


Note: the template is for general graphs or trees, while binary tree is a special case. so the template using dual-stack can be used for binary tree traversal (preorder travelsal and postorder travelsal).


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

3. Restore IP Addresses

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值