Graph Theory 2 of Data Structure experiment: breadth-first search traversal based on the adjacent table Time Limit: 1000 ms memory limit: 65536 k any questions? Click Here ^_^ The topic description gives a undirected connected graph with vertex numbers ranging from 0 to n-1. it traverses through the breadth-first search (BFS) and outputs The traversal Sequence starting from a certain vertex. (The adjacent contacts of the same node and smaller node numbers are preferentially traversed.) input the first behavior integer N (0 <n <100), indicating the number of data groups.
For each group of data, the first row is three integers K, M, T (0 <k <m <(k-1) * k/<t <K ), it indicates that there are m edges and k vertices. t indicates the starting vertex of traversal.
In the following m rows, each row is a space-separated integer U, V, indicating a undirected edge connecting u and v vertex. The output contains N rows, which correspond to N sets of outputs. Each row is a K integer separated by spaces and corresponds to a group of data, which indicates the traversal result of BFS. Sample Input
16 7 00 30 41 41 52 32 43 5
Sample output
0 3 4 2 5 1
The system prompts you to use the adjacent table for storage.
Next, an adjacent linked list is generated. If we want to use an adjacent table to store graphs, first of all, we need to think about why the last time we used an adjacent matrix to store graphs is quite good. If a sparse graph has 10000 nodes, but only Node 1 is connected to node 10000. In this case, we need a 10000*10000 adjacent matrix .. Obviously, this approach is not good. At this time, we need another structure called the adjacent table.
So you can ..
# Include <iostream> # include <queue> # include <cstring> # include <cstdio> # include <set> # include <queue> # include <algorithm> using namespace STD; int vis [222], ANS [222], Q; typedef struct edge // The Graph Set of the adjacent linked list is used to store the container {set <int> S of the node connected to a node; // set is an ordered set. Set is excellent for this question, but I think} g; G P [222]; void addnode (INT U, int V) {P [u]. s. insert (V); P [v]. s. insert (U);} void BFS (INT t) {queue <int> q; vis [T] = 1; ans [q ++] = T; q. push (t); While (! Q. empty () {int v = Q. front (); q. pop (); set <int >:: iterator I = P [v]. s. begin (); While (I! = P [v]. S. End () {If (! Vis [* I]) {vis [* I] = 1; ans [q ++] = * I; q. push (* I) ;}++ I ;}} int main () {int T, K, M, T, I, U, V; CIN> T; while (t --) {q = 0; memset (VIS, 0, sizeof (VIS); CIN> K> m> T; for (I = 0; I <m; I ++) {CIN> U> V; addnode (u, v);} BFS (t); for (I = 0; I <q; I ++) if (I! = Q-1) cout <ans [I] <"; else cout <ans [I] <Endl;} return 0 ;}