LeetCode——复制图

本文详细介绍了使用深度学习方法和图遍历算法进行图像克隆的过程,通过BFS方法实现图的遍历,并利用哈希映射避免重复访问节点。文章以自定义算法实现为例,探讨了节点创建时机的选择,提供了完整代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://articles.leetcode.com/2012/05/clone-graph-part-i.html

BFS方法遍历图。为了防止重复遍历,使用hashmap,key为原图的node,value为新图的node。

我没有看原文的算法实现先是自己想了然后写上去。这样的过程中我碰到了一些问题。比如说什么时候创建新的节点?是在while的开始,还是在遍历相邻节点的时候?这点很重要。


实现:

package com.song.algorithm;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class Image {
	public static class Node {
		public int data;
		public List<Node> neighbors;
	}

	public Node head;

	public static Image copy(Image image) {
		Queue<Node> queue = new LinkedList<Node>();
		if (image.head == null) {
			return null;
		}
		Image cp = new Image();
		HashMap<Node, Node> map = new HashMap<Node, Node>();
		Node newHead = new Node();
		newHead.data = image.head.data;
		cp.head = newHead;
		map.put(image.head, newHead);
		queue.add(image.head);
		while (!queue.isEmpty()) {
			Node node = queue.remove();
			Node cnode = map.get(node);
			if (node.neighbors != null) {
				List<Node> cnodeNeighbors = new ArrayList<Node>();
				cnode.neighbors = cnodeNeighbors;
				for (Node n : node.neighbors) {
					if (map.get(n) == null) {
						Node newNode = new Node();
						newNode.data = n.data;
						map.put(n, newNode);
						cnodeNeighbors.add(newNode);
						queue.add(n);
					} else {
						cnodeNeighbors.add(map.get(n));
					}
				}
			}
		}
		return cp;
	}

	public static void iterate(Image image) {
		HashSet<Node> set = new HashSet<Node>();
		set.add(image.head);
		Queue<Node> queue = new LinkedList<Node>();
		queue.add(image.head);
		while (!queue.isEmpty()) {
			Node node = queue.remove();
			System.out.print(node.data + " ");
			if (node.neighbors != null) {
				for (Node n : node.neighbors) {
					if (!set.contains(n)) {
						queue.add(n);
						set.add(n);
					}
				}
			}
		}
	}

	public static void main(String[] args) {
		Image image = new Image();
		Node head = new Node();
		image.head = head;
		head.data = 1;
		ArrayList<Node> nei1 = new ArrayList<Node>();
		Node n2 = new Node();
		n2.data = 2;
		nei1.add(n2);
		head.neighbors = nei1;
		ArrayList<Node> nei2 = new ArrayList<Node>();
		Node n3 = new Node();
		n3.data = 3;
		nei2.add(n3);
		Node n4 = new Node();
		n4.data = 4;
		nei2.add(n4);
		n2.neighbors = nei2;
		ArrayList<Node> nei3 = new ArrayList<Node>();
		nei3.add(head);
		n4.neighbors = nei3;
		iterate(image);
		System.out.println("");
		Image image1 = copy(image);
		iterate(image1);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值