Graph using adjacency matrix

Adjacency matrix is a 2D array of size n*n where n = no of vertices

Let adj[][] be our adjacency matrix.

If there is an edge from vertex i to vertex j then we say adj[i][j] = 1.
For an undirected graph , adj[i][j] = adj[j][i] = 1

Adjacency matrix can also be used to represent weighted graphs.
If there is an edge from vertex i to vertex j with weight w , then we say adj[i][j] = w

Lets see representation of a directed graph using adjacency matrix.

Graphs-using-adjacency-matrix
edge(u-->v) is represented by adj_mat[u][v] = 1


Code

void read_graph()
{
    int i,j;

    printf("Enter the no of vertices in the graph ");
    scanf("%d",&n);

    printf("\nEnter adjacency matrix\n");

    for(i=1;i<=n;i++)
    {
        for(j=1;j<=n;j++)
            scanf("%d",&adj_mat[i][j]);

        vis[i] = 0;
    }
}

No comments:

Post a Comment