图的存储和遍历

Date:2019-05-16 21:12:35

图的存储

邻接表:

1 struct node
2 {
3     int v;  //编号
4     int w;  //权值
5     node(int _v. int _w) : v(_v), w(_w) {}  //构造函数
6 };
7 vector<node> adj[M];
8 adj[1].push_back(node(3,4));
  • 适合稀疏图,V多E少;

邻接矩阵:

const int M=1e3, INF=1e9;
int grap[M][M];
fill(grap[0],grap[0]+M*M,INF);
  • 适合稠密图,V少E多;
  • 通常顶点数bu超过1e3时考虑用邻接矩阵,否则会超时;

 

图的遍历

DFS:

const int M = 1e3;
const int INF = 1e9;
//邻接矩阵
int n, G[M][M];
bool vis[M]={false};

void DFS(int u, int depth)
{
    vis[u] = true;
    for(int v=0; v<n; v++)
        if(vis[v]==false && G[u][v]!=INF)
            DFS(v,depth+1);
}

void DFSTrave()
{
    for(int u=0; u<n; u++)
        if(vis[u] == false)
            DFS(u, 1);
}

//邻接表
vector<int> Adj[M];
int n;
bool vis[M]={false};

void DFS(int u, int depth)
{
    vis[u] = true;
    for(int i=0; i<Adj[u].size(); i++)
    {
        int v = Adj[u][i];
        if(vis[v] == false)
            DFS(v, depth+1);
    }
}

void DFSTrave()
{
    for(int u=0; u<n; u++)
        if(vis[u] == false)
            DFS(u, 1);
}

 

BFS:

 1 //邻接矩阵
 2 int n, grap[M][M];
 3 bool vis[M]={false};
 4 
 5 void BFS(u)
 6 {
 7     queue<int> q;
 8     q.push(u);
 9     vis[u]=true;
10     while(!q.empty())
11     {
12         u = q.front();  q.pop();
13         for(int v=0; v<n; v++)
14             if(vis[v]==false && grap[u][v]!=INF)
15             {
16                 q.push(v);
17                 vis[v]=true;
18             }
19     }
20 }
21 
22 void BFSTrave()
23 {
24     for(int u=0; u<n; u++)
25         if(vis[u]==false)
26             BFS(u);
27 }
28 
29 //邻接表
30 struct node
31 {
32     int v;
33     int layer;
34 };
35 vector<node> adj[M];
36 int n;
37 bool vis[M]={false};
38 
39 void BFS(int u)
40 {   //求该连通块中其他顶点的层号
41     node start = node(u,0);
42     queue<node> q;
43     q.push(start);
44     vis[u]=true;
45     while(!q.empty())
46     {
47         start = q.front();  q.pop();
48         u = start.v;
49         for(int i=0; i<adj[u].size(); i++)
50         {
51             node next = adj[u][i];
52             next.layer = start.layer+1;
53             if(vis[next.v]==false)
54             {
55                 q.push(next);
56                 vis[next.v]=true;
57             }
58         }
59     }
60 }
61 
62 void BFSTrave()
63 {
64     for(int u=0; u<n; u++)
65     {
66         if(vis[u]==false)
67             BFS(u);
68     }
69 }

 

posted @ 2019-05-16 21:22  林東雨  阅读(537)  评论(0编辑  收藏  举报