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

背景

(以下背景资料转载自: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;

    }
}

代码下载:https://github.com/jimenbian/GarvinLeetCode

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

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

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

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

时间: 2024-08-24 11:51:43

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

【LeetCode从零单排】No118 Pascal&#39;s Triangle

题目 Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5,Return [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] 代码 public class Solution { public List<List<Integer>> generate(int numRows) { List<List

GraphMatrix::BFS广度优先搜索

查找某一结点的邻居: virtual int firstNbr(int i) { return nextNbr(i, n); } //首个邻接顶点 virtual int nextNbr(int i, int j) //相对于顶点j的下一邻接顶点 { while ((-1 < j) && (!exists(i, --j))); return j; } //逆向线性试探(改用邻接表可提高效率) 对于图中的所有顶点,对每一个连通区域进行BFS: template <typename

步步为营(十六)搜索(二)BFS 广度优先搜索

上一篇讲了DFS,那么与之相应的就是BFS.也就是 宽度优先遍历,又称广度优先搜索算法. 首先,让我们回顾一下什么是"深度": 更学术点的说法,能够看做"单位距离下,离起始状态的长度" 那么广度是什么呢? 个人认为,能够这么归纳: 何为广度? 能够看做"距离初始状态距离相等的结点"的集合 那么BFS的核心思想就是:从初始结点開始,搜索生成第一层结点.检查目标结点是否在这些结点中,若没有,再将全部第一层的结点逐一进行搜索,得到第二层结点,并逐一检查

关于宽搜BFS广度优先搜索的那点事

以前一直知道深搜是一个递归栈,广搜是队列,FIFO先进先出LILO后进后出啥的.DFS是以深度作为第一关键词,即当碰到岔道口时总是先选择其中的一条岔路前进,而不管其他岔路,直到碰到死胡同时才返回岔道口并选择其他岔路.接下来将介绍的广度优先搜索(Breadth First Search, BFS)则是以广度为第一关键词,当碰到岔道口时,总是先一次访问从该岔道口能直接到达的所有节结点,然后再按这些结点被访问的顺序去依次访问它们能直接到达的所有结点,以此类推,直到所有结点都被访问为止.这就跟平静的水面

【LeetCode从零单排】No70.ClimbingStairs

题目 爬楼梯问题,这是一道很有趣的问题.首先看题目: You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 这道题一共有三个方法实现(我想到的): 1.递归(对应代码climbStairs) 如果楼梯有n层,我们回退到n-

【LeetCode从零单排】No26.Remove Duplicates from Sorted Array

题目 题目要求:去除sort int数组中的重复项. Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this in place with constant memory. For exam

【LeetCode从零单排】No.7 Reverse Integer

前话 今天开始励志刷一下leetcode上面的题目(还好这个网站没被TG和谐).从easy的开始,数一下差不多有40道,争取两个月搞定. 题目 没想到做的第一道题目,虽然看似简单,却费了很大周折. 题目如下: Reverse digits of an integer. Example1: x = 123, return 321Example2: x = -123, return -321 刚看到这道题,首先蹦出的想法是把整数转换为字符串,然后前后位置换下再转回int型,实事证明这样是不可取的,因

【LeetCode从零单排】No 3 Longest Substring Without Repeating Characters

题目 Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest su

【LeetCode从零单排】No67.AddBinary

题目 Given two binary strings, return their sum (also a binary string). For example,a = "11"b = "1"Return "100". 代码 public class Solution { public String addBinary(String a, String b) { String lon= a.length()-b.length()>=0 ?