Problem Description
Known undirected graph adjacency matrix, the matrix is based to give depth-first search traversal sequence, and to give the number of the connected undirected graph of the component.
When traversing, when there are a plurality of alternative points, a small number of vertices preferred.
Enter a description:
The first line is a positive integer, for the number of vertices n, vertex numbers were 0,1, ..., n-1. Followed adjacency matrix, n rows and n columns.
Output Description:
Total 2 line. The first line is output to the non-depth-first search traversal sequence diagram, the output of vertex numbers, separated by a space between the vertex numbers; the number of the second line without the connected component.
Sample input:
6
0 1 0 0 0 0
1 0 0 0 1 0
0 0 0 1 0 0
0 0 1 0 0 0
0 1 0 0 0 1
0 0 0 0 1 0
Sample Output
0 1 4 5 2 3
2
prompt
In adjacency matrix storage structure, depth-first search run, without counting the number of the connected components in the process of traversal of FIG.
Problem Description
Known undirected graph adjacency matrix, the matrix is based to give depth-first search traversal sequence, and to give the number of the connected undirected graph of the component.
When traversing, when there are a plurality of alternative points, a small number of vertices preferred.
Enter a description:
The first line is a positive integer, for the number of vertices n, vertex numbers were 0,1, ..., n-1. Followed adjacency matrix, n rows and n columns.
Output Description:
Total 2 line. The first line is output to the non-depth-first search traversal sequence diagram, the output of vertex numbers, separated by a space between the vertex numbers; the number of the second line without the connected component.
Sample input:
6
0 1 0 0 0 0
1 0 0 0 1 0
0 0 0 1 0 0
0 0 1 0 0 0
0 1 0 0 0 1
0 0 0 0 1 0
Sample Output
0 1 4 5 2 3
2
prompt
In adjacency matrix storage structure, depth-first search run, without counting the number of the connected components in the process of traversal of FIG.
#include<stdio.h> #include<stdlib.h> bool visited[100]; int G[100][100]; void DFS(int v, int vexnum) { visited[v] = true; printf("%d ", v); for (int i = 0; i < vexnum; i++) { if (visited[i] == false && G[v][i] != 0) DFS(i, vexnum); } } void DFSTraverse(int vexnum) { int i; int count = 0; for ( i = 0; i < vexnum; i++) visited[i] = false; for ( i = 0; i < vexnum; i++) { if (visited[i] == false) { DFS(i, vexnum); count++; } } printf("\n%d\n", count); } int main() { int i, j, vexnum; scanf("%d", & vexnum); for (i = 0; i < vexnum; i++) { for (j = 0; j < vexnum; j++) scanf("%d", &G[i][j]); } DFSTraverse(vexnum); }