To solve the problem, it is convenient to switch from the adjacency list representation to an adjacency matrix of the graph.
Construct an adjacency matrix of size n \times n, where a_{ij} = 1 if there is a directed edge from vertex to vertex , and otherwise.
Next, for each vertex , count the number of incoming edges. This can be done by summing the elements of the -th column of the adjacency matrix.
A vertex is a source if and only if no edges enter it, that is, the sum of the elements in the corresponding column is .
Thus, the answer is the number of vertices for which the number of incoming edges equals zero.
Example
The graph has one source — vertex , since no edges enter it.
Algorithm implementation
Declare an adjacency matrix and an array , where stores the number of edges entering vertex .
#define MAX 101
int g[MAX][MAX], in[MAX];Read the input data. Based on the given adjacency list, construct the adjacency matrix.
scanf("%d", &n);
for (i = 1; i <= n; i++)
{For each vertex , first read the number of outgoing edges .
scanf("%d", &k);
for (j = 0; j < k; j++)
{For each edge , set g[i][x] = 1.
scanf("%d", &x);
g[i][x] = 1;
}
}Iterate over all pairs of vertices, traversing the adjacency matrix. For each edge , increment by , since the edge enters vertex .
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
if (g[i][j] == 1) in[j]++;Count the number of source vertices — that is, vertices with no incoming edges (for which in[i] = 0).
int source = 0;
for (i = 1; i <= n; i++)
if (in[i] == 0) source++;Print the answer.
printf("%d\n", source);