浙大数据结构:06-图1 列出连通集

这道题就是建图并熟悉一下dfs和bfs,比较简单

1、条件准备

存图准备,用邻接矩阵,visit看该结点是否走过
#include <iostream>
#include <string.h>
using namespace std;

int n, m;//结点数,边数
int graph[20][20];//邻接矩阵存
int visit[15];//是否访问该节点
主函数先输入结点数和边数,然后存图,无向图存两次。
然后dfs遍历输出每一个连通集,然后visit置0,再bfs每一个连通集,注意输出格式。 

int main()
{
  ios::sync_with_stdio(false);
  cin.tie(0), cout.tie(0);
  cin >> n >> m;
  for (int i = 0; i < m; i++)
  {
    int a, b;
    cin >> a >> b;
    graph[a][b] = 1;graph[b][a] = 1;
  }

  for (int i = 0; i < n; i++)
  {
    if (!visit[i])
    {
      cout << "{ ";
      dfs(i);
      cout << "}";
      cout << endl;
    }
  }
  memset(visit, 0, sizeof(visit));

  for (int i = 0; i < n; i++)
  {
    if (!visit[i])
    {
      cout << "{ ";
      bfs(i);
      cout << "}";
      cout << endl;
    }
  }
  return 0;
}

2、dfs遍历

dfs使用递归实现,访问到该节点就输出,visit置1.
然后遍历所有结点,如果没走过并且有路就走。
void dfs(int x)
{
  cout << x << ' ';
  visit[x] = 1;
  for (int i = 0; i < n; i++)
    if (!visit[i] && graph[x][i])
      dfs(i);
}

3、bfs遍历

用数组模拟队列来进行bfs,先把头存入队列并输出。
然后遍历队列直到为空,每一次循环先取队头,再遍历所有结点。
若没走过且有路则输出并放入队列中。
void bfs(int head)
{
  int q[20], tt = -1, hh = 0;
  q[++tt] = head;
  visit[head] = 1;
  cout << head << ' ';
  while (hh <= tt)
  {
    int cur = q[hh++];
    for (int i = 0; i < n; i++)
    {
      if (!visit[i] && graph[cur][i])
      {
        cout << i << " ";
        visit[i] = 1;
        q[++tt] = i;
      }
    }
  }
}

4、总结

这题较为简单,难度不大。
完整代码如下:
#include <iostream>
#include <string.h>
using namespace std;

int n, m;
int graph[20][20];
int visit[15];

void dfs(int x)
{
  cout << x << ' ';
  visit[x] = 1;
  for (int i = 0; i < n; i++)
    if (!visit[i] && graph[x][i])
      dfs(i);
}

void bfs(int head)
{
  int q[20], tt = -1, hh = 0;
  q[++tt] = head;
  visit[head] = 1;
  cout << head << ' ';
  while (hh <= tt)
  {
    int cur = q[hh++];
    for (int i = 0; i < n; i++)
    {
      if (!visit[i] && graph[cur][i])
      {
        cout << i << " ";
        visit[i] = 1;
        q[++tt] = i;
      }
    }
  }
}

int main()
{
  ios::sync_with_stdio(false);
  cin.tie(0), cout.tie(0);
  cin >> n >> m;
  for (int i = 0; i < m; i++)
  {
    int a, b;
    cin >> a >> b;
    graph[a][b] = 1;graph[b][a] = 1;
  }

  for (int i = 0; i < n; i++)
  {
    if (!visit[i])
    {
      cout << "{ ";
      dfs(i);
      cout << "}";
      cout << endl;
    }
  }
  memset(visit, 0, sizeof(visit));

  for (int i = 0; i < n; i++)
  {
    if (!visit[i])
    {
      cout << "{ ";
      bfs(i);
      cout << "}";
      cout << endl;
    }
  }
  return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值