【问题标题】:Randomly add INFTY value in adjacency matrix在邻接矩阵中随机添加 INFTY 值
【发布时间】:2016-01-08 17:09:59
【问题描述】:

我想创建一个表示无向图的邻接矩阵(以实现 Dijkstra 算法)。我通过创建填充随机数的 N*N 矩阵开始我的代码。但是,它希望使图形不是完全连接的,因此矩阵必须包含 INFTY,表示任何节点对之间没有路径。因此,如何随机在矩阵生成过程中添加INFNTY值如下:

#include <stdio.h> 
#include <string.h> 
#include <time.h>
#include <math.h>

#define INFTY 99  // Define Infinity as a macro

int main (int argc, char* argv[]) {
        /* Local Variables */
    int N = 40;             // Number of Nodes
    int SOURCE = 0;         // Selected Source
    int i,j;

    /* Matrix Allocation for edges */
    int *edge[N]; 
    for (i = 0; i < N; i++){
        edge[i] = malloc(N * sizeof(int));
    }

    /* Randomely fill the matrix with random integers from 0-10 */
    srand(0);
    for (i = 0; i < N; i++){
        for (j = 0; j < N; j++){
            if(i == j)
                edge[i][j] = 0;
            else
                edge[i][j] = rand() % 10; // Can I do something here to insert INFTY randomly. 
        }
    }
}

【问题讨论】:

  • 路径使用负值或其他数据结构(列表列表)而不是矩阵
  • 我想过,但你知道 Dijkstra 算法不能处理负值。
  • 那又怎样?您不需要处理它们,但忽略它们。您也可以只使用一些定义的最大值(定义您自己的) - 这应该不是问题
  • 发布的代码没有完全编译。编译时始终启用所有警告。 (对于 gcc,至少使用:-Wall -Wextra -pedantic)然后修复警告。除其他问题外,srand() 函数的代码缺少#include &lt;stdlib.h&gt;。 main() 的两个参数未使用。建议:int main( void ) 变量“SOURCE”未使用。建议删除该变量。
  • 在询问有关运行时问题的问题时,发布干净编译但仍然存在问题的代码。

标签: c algorithm matrix random


【解决方案1】:

这是 Dijkstra 算法的一种实现。

基本实现取自:http://code.geeksforgeeks.org/index.php

注意:没有 malloc,没有 free,没有深奥的代码。

#define V (9)控制的图形大小很容易改变大小

此算法适用于单个source,您可能希望将其扩展为使用多个来源。

// A C program for Dijkstra's single source shortest path algorithm.
// The program is for adjacency matrix representation of the graph

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <stdbool.h>
#include <time.h>

// Number of vertices in the graph
#define V (9)

// A utility function to find the vertex with minimum distance value, from
// the set of vertices not yet included in shortest path tree
int minDistance(int dist[], bool sptSet[])
{
    // Initialize min value
    int min = INT_MAX, min_index;
    int v;
    for (v = 0; v < V; v++)
        if (sptSet[v] == false && dist[v] <= min)
            min = dist[v], min_index = v;

    return min_index;
}

// A utility function to print the constructed distance array
void printSolution(int dist[], int n)
{
    printf("Vertex Distance from Source\n");

    int i;
    for (i = 0; i < n; i++)
    {
        printf("%d \t\t %d\n", i, dist[i]);
    }
}

// Function that implements Dijkstra's single source shortest path algorithm
// for a graph represented using adjacency matrix representation
void dijkstra(int graph[V][V], int src)
{
    int dist[V];     // The output array. dist[i] will hold the shortest
                    // distance from src to i

    bool sptSet[V]; // sptSet[i] will true if vertex i is included in shortest
                    // path tree or shortest distance from src to i is finalized

    // Initialize all distances as INFINITE and stpSet[] as false
    int i;
    for (i = 0; i < V; i++)
        dist[i] = INT_MAX, sptSet[i] = false;

    // Distance of source vertex from itself is always 0
    dist[src] = 0;

    // Find shortest path for all vertices
    int count;
    for (count = 0; count < V-1; count++)
    {
    // Pick the minimum distance vertex from the set of vertices not
    // yet processed. u is always equal to src in first iteration.
    int u = minDistance(dist, sptSet);

    // Mark the picked vertex as processed
    sptSet[u] = true;

    // Update dist value of the adjacent vertices of the picked vertex.
    int v;
    for (v = 0; v < V; v++)

        // Update dist[v] only if is not in sptSet, there is an edge from
        // u to v, and total weight of path from src to v through u is
        // smaller than current value of dist[v]
        if (    !sptSet[v] 
             && graph[u][v] 
             && dist[u] != INT_MAX
             && dist[u]+graph[u][v] < dist[v]
           )
        {
            dist[v] = dist[u] + graph[u][v];
        }
    }

    // print the constructed distance array
    printSolution(dist, V);
}

// driver program to test above function
int main( void )
{
    int graph[V][V];

    srand( time(NULL) );

    int i; // loop counter
    int j; // loop counter

    for( i=0; i<V; i++) // row loop
    {
        for( j=0; j<V; j++) // column loop
        {
            graph[i][j] = rand() % V; // yields values in range 0..(V-1)
        }
    }

    dijkstra(graph, 0);

    return 0;
}

【讨论】:

    【解决方案2】:

    你可以这样做:

    for (i = 0; i < N; i++){
        for (j = 0; j < N; j++){
            if(i == j)
                edge[i][j] = 0;
            else {
                int r = rand() % 11
                edge[i][j] = r == 10 ? INFTY : r;
            }
    }
    

    这意味着大约每 11 个边都是INF。如果你想增加矩阵的稀疏性,你可以:

    int sparsity_rate = 50; // measured in %
    ...
    if (rand() % 1011 <= sparsity_rate)
        edge[i][j] = INFTY;
    else
        edge[i][j] = rand() % 10;
    

    sparsity_rate 告诉您图表的空闲程度(以 % 为单位)。在上面的示例中,大约 50% 的边缘会消失。

    【讨论】:

    • 感谢您的帮助。这就是我一直在寻找的。​​span>
    • @MidoKammi 我总是很乐意提供帮助 :)
    • 什么是INF 值?为什么不直接使用 10 作为 INF?
    • @user3629249 有一个错字。 INF 应该是他的INFTY
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-08
    • 2013-02-12
    • 2020-10-02
    • 2016-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多