求助图的遍历DFS
  • 板块学术版
  • 楼主Carrot_Rui
  • 当前回复6
  • 已保存回复6
  • 发布时间2023/10/27 11:10
  • 上次更新2023/11/2 11:15:41
查看原帖
求助图的遍历DFS
376481
Carrot_Rui楼主2023/10/27 11:10

这题我用链式向前写的图的遍历,写了好几个数据dfs大部分是错的,大佬看看为什么。

我sort将数组从大到小排序,这样遍历链表的时候就可以从小到大遍历(因为我这链表是直接插到头节点后面)

只有20分QAQ

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

const int N = 1000060;

int h[N], n, m;
int e[N], ne[N], idx;
bool vis[N];

void insert(int a, int b){
	e[idx] = b; ne[idx] = h[a]; h[a] = idx ++;
}

void dfs(int u){
	vis[u] = true;
	cout << u << ' ';
	
	for(int i = h[u]; i != -1; i = ne[i]){
		int j = e[i];
		if(!vis[j]){
			dfs(j);
		}
	}
}

struct fn{
	int x, y;
}a[N];

bool cmp(fn a, fn b){
	if(a.x == b.x) return a.y > b.y;
	return a.x < b.x;
}

int q[N], hh, tt = -1;

void bfs(int u){
	memset(vis, 0, sizeof vis);
	vis[u] = 1;
	q[++ tt] = u; 
	
	while(hh <= tt){
		int x = q[hh ++]; // 取出队头
		for(int i = h[x]; i != -1; i = ne[i]){
			int j = e[i];
			if(!vis[j]){
				q[++ tt] = j;
				vis[j] = 1;
			}
		}
		cout << x << ' ';
	}
	
}

int main(){
	cin >> n >> m;
	memset(h, -1, sizeof h);
	
	for(int i = 1; i <= m; i ++)
		cin >> a[i].x >> a[i].y;
	
	sort(a + 1, a + 1 + m, cmp);
	
	for(int i = 1; i <= n; i ++){
		insert(a[i].x, a[i].y);
	}
	
	dfs(1);
	puts("");
	bfs(1);
	puts("");
	
	return 0;
}

/*
  8 12
  1 2
  1 3
  1 6
  2 4
  2 5
  4 5
  4 8
  5 7
  3 7
  3 6
  3 8
  6 8
  期望:
  1 2 4 5 7 8 3 6
  1 2 3 6 4 5 7 8
 */

/*
  5 6
  1 2
  1 3
  1 4
  2 3
  4 5
  2 5
  期望:
  1 2 5 3 4
  1 2 3 4 5
 */
2023/10/27 11:10
加载中...