码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode从零单排】No133. clon graph (BFS广度优先搜索)

时间:2015-04-06 17:16:36      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:java   leetcode   

背景

(以下背景资料转载自:http://www.cnblogs.com/springfor/p/3874591.html?utm_source=tuicool)
DFS(Dpeth-first Search)
顾名思义,就是深度搜索,一条路走到黑,再选新的路。
记得上Algorithm的时候,教授举得例子就是说,DFS很像好奇的小孩,你给这个小孩几个盒子套盒子,好奇的小孩肯定会一个盒子打开后继续再在这个盒子里面搜索。
等把这一套盒子都打开完,再打开第二套的。
Wikipedia上的讲解是:“Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data structures.
One starts at the root (selecting some arbitrary node as the root in the case of a graph) and explores as far as possible
along each branch before backtracking.”
通常来说简便的DFS写法是用递归,如果非递归的话就是栈套迭代,思想是一样的。
递归写法的DFS伪代码如下:
Input: A graph G and a root v of G
1   procedure DFS(G,v):
2       label v as discovered
3       for all edges from v to w in G.adjacentEdges(v) do
4           if vertex w is not labeled as discovered then
5               recursively call DFS(G,w)
非递归写法的DFS伪代码如下:
Input: A graph G and a root v of G
技术分享
1   procedure DFS-iterative(G,v):
2       let S be a stack
3       S.push(v)
4       while S is not empty
5             v ← S.pop() 
6             if v is not labeled as discovered:
7                 label v as discovered
8                 for all edges from v to w in G.adjacentEdges(v) do
9                     S.push(w)
技术分享



BFS(Breadth-first Search)
这个就是相对于BFS的另外一种对图的遍历方法,对于一个节点来说先把所有neighbors都检查一遍,再从第一个neighbor开始,循环往复。
由于BFS的这个特质,BFS可以帮助寻找最短路径。
Wikipedia上面对BFS的定义是:
“In graph theory, breadth-first search (BFS) is a strategy for searching in a graph when search is limited to essentially two operations: (a) visit and inspect a node of a graph; (b) gain access to visit the nodes that neighbor the currently visited node. The BFS begins at a root node and inspects all the neighboring nodes. Then for each of those neighbor nodes in turn, it inspects their neighbor nodes which were unvisited, and so on. Compare BFS with the equivalent, but more memory-efficient
Iterative deepening depth-first search and contrast with depth-first search.”


题目

Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.


OJ‘s undirected graph serialization:

Nodes are labeled uniquely.

We use # as a separator for each node, and , as a separator for node label and each neighbor of the node.

As an example, consider the serialized graph {0,1,2#1,2#2,2}.

The graph has a total of three nodes, and therefore contains three parts as separated by #.

  1. First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
  2. Second node is labeled as 1. Connect node 1 to node 2.
  3. Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.

Visually, the graph looks like the following:

       1
      /      /       0 --- 2
         /          \_/

总之就是遍历搜有的路径,然后再一个一个节点添加进去。


代码

/**
 * Definition for undirected graph.
 * class UndirectedGraphNode {
 *     int label;
 *     List<UndirectedGraphNode> neighbors;
 *     UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
 * };
 */
public class Solution {
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        if (node==null) return null;
        HashMap<UndirectedGraphNode,UndirectedGraphNode> hm=new HashMap<UndirectedGraphNode,UndirectedGraphNode>();
        LinkedList<UndirectedGraphNode> queue=new LinkedList<UndirectedGraphNode>();
        UndirectedGraphNode head = new UndirectedGraphNode(node.label);
        hm.put(node, head);
        queue.add(node);
        while(!queue.isEmpty()){
             UndirectedGraphNode current=queue.poll();
        	     for(UndirectedGraphNode neighbor:current.neighbors){
        	    	      if(!hm.containsKey(neighbor)){
        	    	    	      queue.add(neighbor);
        	    	    	      UndirectedGraphNode temp=new UndirectedGraphNode(neighbor.label);
        	    	    	      hm.put(neighbor,temp);
        	    	      }
        	    	      hm.get(current).neighbors.add(hm.get(neighbor));
        	     }
        }
        
        return head;
        
        
    }
}



/********************************

* 本文来自博客  “李博Garvin“

* 转载请标明出处:http://blog.csdn.net/buptgshengod

******************************************/




【LeetCode从零单排】No133. clon graph (BFS广度优先搜索)

标签:java   leetcode   

原文地址:http://blog.csdn.net/buptgshengod/article/details/44903337

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!