随机连接图生成器

时间:2016-08-24 00:12:41

标签: c# algorithm random graph

我正在尝试通过随机连接N个节点来生成一个简单的图形。我正在寻找有效的算法,如下所示:

  • 输入:
    • N个节点数
    • EN-1N(N-1)/2
    • 的边数
  • 输出:具有N个顶点和E个边缘的简单连通图

2 个答案:

答案 0 :(得分:2)

创建N个节点的数组。 Fisher-Yates shuffle数组。扫描阵列并为阵列中相邻的每对节点创建边缘。结果是带有N-1边的连通图。

如果附加边的数量很少,那么你可以随意添加边,直到你有足够的边。否则,创建一个未使用边的数组,Fisher-Yates对数组进行洗牌,并从数组中取出第一个(E - (N-1))边。

答案 1 :(得分:-1)

这是一个非常简单的算法,可以随机连接每个节点和随机数量的其他节点。

//
//  NSCoder.swift
//  NoodleKit
//
//  Created by Thom Morgan on 8/15/16.
//  Copyright © 2016 CocoaPods. All rights reserved.
//

// MARK: - ** Import Modules **

import Foundation

// MARK: - ** NSCoder - _ObjectiveCBridgeable Encoding Compatibility **

extension NSCoder {

    /// Encodes an `_ObjectiveCBridgeable` data structure.
    /// - important: The objective-c class being bridged to must conform to
    /// `NSCoding`.
    /// - parameter object: The object to encode.
    public func encodeObject<T: _ObjectiveCBridgeable>(object: T?) {
        encodeObject(object?._bridgeToObjectiveC())
    }

    /// Encodes an `_ObjectiveCBridgeable` data structure as a root object.
    /// - important: The objective-c class being bridged to must conform to
    /// `NSCoding`.
    /// - parameter object: The object to encode.
    public func encodeRootObject<T: _ObjectiveCBridgeable>(object: T) {
        encodeRootObject(object._bridgeToObjectiveC())
    }

    /// Encodes an `_ObjectiveCBridgeable` conditional data structure.
    /// - important: The objective-c class being bridged to must conform to
    /// `NSCoding`.
    /// - parameter object: The object to encode.
    public func encodeConditionalObject<T: _ObjectiveCBridgeable>(object: T?) {
        encodeConditionalObject(object?._bridgeToObjectiveC())
    }

    /// Encodes an `_ObjectiveCBridgeable` data structure and maps it to a 
    /// specific `key`.
    /// - important: The objective-c class being bridged to must conform to
    /// `NSCoding`.
    /// - parameter object: The object to encode.
    /// - parameter key: The key to associate with this object.
    public func encodeObject<T: _ObjectiveCBridgeable>(object: T?, forKey key: String) {
        encodeObject(object?._bridgeToObjectiveC(), forKey: key)
    }

    /// Encodes an `_ObjectiveCBridgeable` conditional data structure and maps
    /// it to a specific `key`.
    /// - important: The objective-c class being bridged to must conform to
    /// `NSCoding`.
    /// - parameter object: The object to encode.
    /// - parameter key: The key to associate with this object.
    public func encodeConditionalObject<T: _ObjectiveCBridgeable>(object: T?, forKey key: String) {
        encodeConditionalObject(object?._bridgeToObjectiveC(), forKey: key)
    }

}