两个着色广度优先搜索

时间:2014-11-20 07:18:12

标签: graph-algorithm breadth-first-search

在标准BFS实现中,节点可以是三种颜色中的一种,以表示它是未被发现,被发现但是不完整,还是被发现和完成。有没有办法只使用两种颜色而不是三种颜色来实现BFS?

1 个答案:

答案 0 :(得分:1)

是的,您只能用两种颜色来表示它。实际上,在99%的问题中,你不需要第三种颜色。你需要得到一个答案:节点X是否在队列中? 要回答这个问题,我们需要一个数组。假设我们称该数组已被访问。

此数组可以包含的值为0或1。

访问[X] = 1,如果节点X在队列中(节点X正在等待处理)或节点在队列中(这意味着节点X当前正在处理,或者已经处理完毕,我们就完成了与该节点) 如果节点X尚未进入队列

,则访问[X] = 0

这是一段代码:

#include <cstdio>
#include <cstdlib>
#include <vector>
#include <queue>

using namespace std;
const int N = 10003;

char visited[N];
queue<int> q;
vector<int> ls[N];

int main() {

  int n, m; scanf("%d%d", &n, &m); // number of vertices and number of edges
  for(int i = 0; i < m; ++i) {
    int x, y; scanf("%d%d", &x, &y);
    ls[x].push_back(y);
    ls[y].push_back(x);
  }

  int num_of_components = 0;

  for(int i = 1; i <= n; ++i) // iterating through all nodes
    if(!visited[i]) { // if we didn't visit node i , then this is a new component

      visited[i] = '1'; // mark node as visited
      q.push(i); // push node to queue
      ++num_of_components; // new component was found, so add one

      while(!q.empty()) {
        int x = q.front();
        q.pop();

        int sz = ls[x].size();
        for(int j = 0; j < sz; ++j) {
          int y = ls[x][j];
          if(!visited[y]) {
            visited[y] = '1';
            q.push(y);
          }
        }
      }
    }

  printf("%d\n", num_of_components);
  return 0;
}
相关问题