2015-05-26 107 views
-1

說我有以下原始數據:如何從輸入創建一個鄰接矩陣?

5 6 
1 4 5 
2 4 5 
2 3 4 
3 4 6 

其中第一行表示:[number of vertices] [number of edges]和隨後的線表示:[index of vertex1] [index of vertex2] [weight]。我正在考慮做%3並將數據劃分爲3個字符串作爲頂點1,頂點2和權重,但是我無法找到將這些數據安排到鄰接矩陣中的正確方法。有什麼建議麼?

+1

你試過谷歌? –

+0

你知道你的鄰接矩陣應該是什麼樣子嗎? –

+0

當然我是這麼做的,我只是困惑了一下,也是新來的C so(yea ik) – jimo

回答

0

Probbaly你需要這個:

#include <stdio.h>  

#define MAXVERTICES 10  

int main(void) 
{  
    int matrix[MAXVERTICES][MAXVERTICES]; 

    for (int i = 0; i < MAXVERTICES; i++) 
    for (int j = 0; j < MAXVERTICES; j++) 
     matrix[i][j] = 0; 

    int nbvertices, nbedges;  
    scanf("%d %d", &nbvertices, &nbedges); 

    for (int i = 0; i < nbvertices; i++) 
    { 
    int v1, v2; 
    int weight; 
    scanf("%d %d %d", &v1, &v2, &weight);  
    matrix[v2][v1] = matrix[v1][v2] = weight; 
    } 

    return 0; 
} 

這是非常基本的,沒有進行錯誤檢查和頂點的最大數量爲10(MAXVERTICES)。