You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C语言统计20×20邻接矩阵各顶点的1的数量并按格式输出

Got it, let's get this sorted. You need to count the number of 1s in each row of your 20x20 adjacency matrix (which gives the edge count per vertex) and output it in that specific format. Here's a complete implementation that builds on your existing code, including generating a random adjacency matrix (since your code has a placeholder for that) and handling the counting/output:

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define M 20
#define N 20

int main() {
    int i, j;
    int G[M][N] = { { 0 } };
    
    // Seed random number generator for unique graphs each run
    srand(time(NULL));
    
    // Create random undirected adjacency matrix (no self-loops)
    for (i = 0; i < M; i++) {
        for (j = i + 1; j < N; j++) {
            // Randomly assign 0 or 1 to represent absence/presence of an edge
            G[i][j] = rand() % 2;
            G[j][i] = G[i][j]; // Mirror values for undirected graph symmetry
        }
    }
    
    // Count edges per vertex and output in the required format
    printf("Number of edges for each node: ");
    for (i = 0; i < M; i++) {
        int edge_count = 0;
        // Iterate through all columns in the current vertex's row
        for (j = 0; j < N; j++) {
            if (G[i][j] == 1) {
                edge_count++;
            }
        }
        // Print the vertex number and its edge count
        printf("Vertex %d: %d ", i, edge_count);
    }
    printf("\n");
    
    return 0;
}

Breakdown of how this works:

  1. Random Matrix Generation:

    • We use srand(time(NULL)) to seed the random number generator so you get a different graph every time you run the program.
    • The nested loops create an undirected graph by mirroring values across the matrix diagonal (since edges go both ways in undirected graphs) and skip self-loops (where i == j). If you need a directed graph instead, replace this section with two full loops (from 0 to 19 for both i and j) and assign G[i][j] independently without mirroring.
  2. Edge Counting:

    • For each vertex (each row in the matrix), we initialize a counter to 0. We then loop through every column in that row, incrementing the counter each time we find a 1 (which represents an edge to another vertex).
  3. Output:

    • We print the results exactly in the format you specified, concatenating each vertex's count into a single line as requested.

If you already have a pre-defined adjacency matrix (instead of generating a random one), you can simply remove the random generation section and use your existing matrix directly.

内容的提问来源于stack exchange,提问作者mugglepot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:11:28