A walk is an alternating sequence of vertices and edges, beginning and ending with a vertex, where each vertex is incident to both the edge that precedes it and the edge that follows it in the sequence, and where the vertices that precede and follow an edge are the end vertices of that edge. The length 'k' of a walk is the number of edges that it uses.
Hint: It might be useful to observe that the number of k-length walks between any two vertices vi and vj in G is the i-jth entry of Ak, where A is the adjacency matrix of G.
Given a simple graph G=(V,E) using adjacency matrix representation taught in the lectures and a positive integer k, output the number of
k-length walks in G with the following exceptions:
k-length walks in G with the following exceptions:
1. Avoid walks that start and end at the same vertex (i.e., do not count diagonal elements).
2. The same walk should not be counted twice, e.g., treat 1 - 2 - 3 and 3 - 2 - 1 as the same walk (i.e., total number of walks divided by 2).
INPUT:
Number of vertices : n (a positive integer)
Value k (a positive integer)
Adj Matrix A of G : n x n (each entry is a 0 or a 1)
OUTPUT:
A single integer indicating the number of k-length walks in G.
#include <stdio.h> #include <stdlib.h> typedef struct mat{ int** matValues; }matrixType; matrixType initializeMatrix(matrixType anyMatrix, int numVertices){ int i, j; anyMatrix.matValues = (int**) calloc(numVertices, sizeof(int*)); for (i=0; i<numVertices; i++) anyMatrix.matValues[i] = (int*) calloc(numVertices, sizeof(int)); for (i=0;i<numVertices;i++) for (j=0; j<numVertices;j++){ anyMatrix.matValues[i][j] = 0; } return anyMatrix; } matrixType multiply(matrixType M1, matrixType M2, int numVertices){ int i,j,k; matrixType resultMatrix; resultMatrix = initializeMatrix(resultMatrix,numVertices); for (i=0;i<numVertices;i++){ for (j=0;j<numVertices;j++){ resultMatrix.matValues[i][j] = 0; for (k=0;k<numVertices;k++){ resultMatrix.matValues[i][j] = resultMatrix.matValues[i][j]+M1.matValues[i][k]*M2.matValues[k][j]; } } } return resultMatrix; } int main() { int m,n,i,j,l,count=0; matrixType a,b,c; scanf("%d %d",&m,&n); a=initializeMatrix(a,m); b=initializeMatrix(b,m); c=initializeMatrix(c,m); for(i=0;i<m;i++) { for(j=0;j<m;j++) { scanf("%d", &a.matValues[i][j]); b.matValues[i][j]=a.matValues[i][j]; } } for(l=2;l<=n;l++) { if(l>2) { for(i=0;i<m;i++) { for(j=0;j<m;j++) { b.matValues[i][j]=c.matValues[i][j]; } } } c = multiply(b, a , m); } if(n==1) { for(i=0;i<m;i++) { for(j=0;j<m;j++) { if(i!=j) count+=a.matValues[i][j]; } } } else { for(i=0;i<m;i++) { for(j=0;j<m;j++) { if(i!=j) count+=c.matValues[i][j]; } } } printf("%d", count/2); return 0; }
No comments:
Post a Comment