图的存储和遍历

/*************************
 * @author xiaolin
 * @date 2023-4-2
 * 图的存储
 ***********************/
#include <iostream>
#include <vector>
using namespace std;
const int INF = 0x3f3f3f3;
const int num = 10;
// 1. 邻接矩阵
int graph[num][num];
/*
 graph[i][j] = INF --> i j 之间无边
 graph[i][j] == graph[j][i]  无向
 graph[i][j] != graph[j][i]  有向
 权值 w = graph[i][j]
 空间复杂度高,不能存储重边
*/
// 2. 邻接表
struct edge
{
    int from, to, w; //起点 终点 权
    edge(int f, int t, int ww):
        from(f), to(t), w(ww)
    {}
};

vector<edge> e[num];

void init(vector<edge> e[])
{
    for(int i=0;i<num;i++)
        e[i].clear();
}

void add(vector<edge> e[], int a, int b, int c)
{
    e[a].push_back(edge(a, b, c) );
}

// 3. 链式前向星
const int Num = 1000005;
struct Edge
{
    int to, next, w; 
}ed[Num];
int head[Num];
int cnt = 0;
void Init()
{
    for(int i=0;i<Num;i++){
        head[i] = -1;
        ed[i].next = -1;
    }
}

void Add(int u, int v, int ww)
{
    ed[cnt].to = v;
    ed[cnt].w = ww;
    ed[cnt].next = head[u];  //以后加节点作为第一个节点
    head[u] = cnt;
    cnt ++ ;

}

void bl(int u)
{
    for(int i=head[u]; i!=-1;i = ed[i].next){

    }
}
// 不方便删除节点
int main()
{

    
}

/**************************
 * @author xiaolin
 * @date 2023-4-2
 * 遍历 & 连通性
*************************/
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
const int num = 100005;
// 邻接表
struct edge
{
	int from, to, w;
	edge(int a, int b, int c):
	    from(a), to(b), w(c)
	{}
};
vector<edge> e[num];
void init()
{
    for(int i=0;i<num;i++)
    	e[i].clear();
}

void add(int a, int b, int w)
{
   e[a].push_back(edge(a, b, w));
}

int vis[num];

bool dfs(int u, int &nmax)  
{
	//cout <<  u << " 被访问" << endl;
    for(int i=0;i<e[u].size();i++){
    	int v = e[u][i].to;
    	if(!vis[v]){
    		return dfs(v, nmax);
    	}
    }
    return true;

}

void bfs(int u)
{
	queue<int> q;
	q.push(u);
	while(!q.empty()){
		int x = q.front();
		q.pop();
		vis[x] = 1;
		cout << x << "被访问" << endl;
		for(int i=0;i<e[x].size();i++){
			if(!vis[e[x][i].to]) 
				q.push(e[x][i].to);
		}
	}
}
int main()
{
    int n, m, a, b;
    cin >> n >> m;
    for(int i=0;i<m;i++){
    	cin >> a >> b;
    	add(a, b, 1);
	}
	for(int i=0;i<=n;i++)
		vis[i] = 0;
    bfs(1);
	 return 0;
}
posted @ 2023-04-02 20:03  小麟qwq  阅读(8)  评论(0)    收藏  举报