leetcode 133 clone-graph 克隆图(图的遍历算法)

题目描述

克隆一个无向图. 图中每个节点包括一个 label 和一个放置其邻居的 list.

节点结构体定义如下:

class UndirectedGraphNode {
	int label;
	ArrayList<UndirectedGraphNode> neighbors;

	UndirectedGraphNode(int x) {
		label = x;
		neighbors = new ArrayList<UndirectedGraphNode>();
	}
}

比如:

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

题目分析

本题考察的是图的遍历,BFS和DFS

BFS ,Java实现,借助队列

public class Solution {
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        
        Map<UndirectedGraphNode,UndirectedGraphNode> map = new HashMap<UndirectedGraphNode,UndirectedGraphNode>();
        //队列,放置遍历的节点
        Queue<UndirectedGraphNode> nodeQueue = new LinkedList<UndirectedGraphNode>();
        nodeQueue.offer(node);
        
        while(nodeQueue.size() != 0){
            
            UndirectedGraphNode tempNode = nodeQueue.poll();
            if(map.containsKey(tempNode)) continue;
            UndirectedGraphNode copyNode = new UndirectedGraphNode(tempNode.label);
            
            for(UndirectedGraphNode unode : tempNode.neighbors){
                copyNode.neighbors.add(unode);
                if(map.containsKey(node)) continue;
                nodeQueue.offer(unode);
            }
            map.put(tempNode,copyNode);
        }
        
        return map.get(node);
    }  
}

DFS,java实现,借助栈,其实与BFS及其类似,只是借助了栈进行遍历之后,顺序不同而已

public class Solution {
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        
        if(node == null) return null;
        
        HashMap<UndirectedGraphNode,UndirectedGraphNode> map = new HashMap<UndirectedGraphNode,UndirectedGraphNode>();
        //栈,放入遍历的节点
        Stack<UndirectedGraphNode> nodeStack = new Stack<UndirectedGraphNode>();
        nodeStack.push(node);
        
        while(!nodeStack.empty()){
            
            UndirectedGraphNode tempNode = nodeStack.pop();
            if(map.containsKey(tempNode)) continue;
            UndirectedGraphNode copyNode = new UndirectedGraphNode(tempNode.label);
            
            for(UndirectedGraphNode unode : tempNode.neighbors){
                copyNode.neighbors.add(unode);
                if(map.containsKey(node)) continue;
                nodeStack.push(unode);
            }
            map.put(tempNode,copyNode);
        }
        
        return map.get(node);
    }
}

    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/bw_yyziq/article/details/79800527
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞