(PAT 1154) Vertex Coloring (图的广度优先遍历)

proper vertex coloring is a labeling of the graph’s vertices with colors such that no two vertices sharing the same edge have the same color. A coloring using at most k colors is called a (proper) k-coloring.

Now you are supposed to tell if a given coloring is a proper k-coloring.

Input Specification:

Each input file contains one test case. For each case, the first line gives two positive integers N and M (both no more than 10​4​​), being the total numbers of vertices and edges, respectively. Then M lines follow, each describes an edge by giving the indices (from 0 to N−1) of the two ends of the edge.

After the graph, a positive integer K (≤ 100) is given, which is the number of colorings you are supposed to check. Then Klines follow, each contains N colors which are represented by non-negative integers in the range of int. The i-th color is the color of the i-th vertex.

Output Specification:

For each coloring, print in a line k-coloring if it is a proper k-coloring for some positive k, or No if not.

Sample Input:

10 11
8 7
6 8
4 5
8 4
8 1
1 2
1 4
9 8
9 1
1 0
2 4
4
0 1 0 1 4 1 0 1 3 0
0 1 0 1 4 1 0 1 0 0
8 1 0 1 4 1 0 5 3 0
1 2 3 4 5 6 7 8 8 9

Sample Output:

4-coloring
No
6-coloring
No

解题思路:

k着色问题,任意相邻的两个顶点之间不能有相同的颜色

利用广度优先遍历图即可,一个顶点和它每个相邻顶点的颜色都不相同。出现相同的情况之间返回false

至于k怎么得到,利用一个set来存储颜色即可

#include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
#include <set>
#include <string.h>
using namespace std;
int colorhashMap[10010];
class gGraph {
public:
	int n;
	vector<int>* edges;
	bool* visited;
public:
	gGraph(int _n) {
		n = _n;
		edges = new vector<int>[n];
		visited = new bool[n];
	}
	void gInsert(int x, int y) {
		edges[x].push_back(y);
		edges[y].push_back(x);
	}

	bool BFS(int start_node) {
		queue<int> bfs_queue;
		visited[start_node] = true;
		bfs_queue.push(start_node);
		while (!bfs_queue.empty()) {
			int tempNode = bfs_queue.front();
			bfs_queue.pop();
			for (int adj_node : edges[tempNode]) {
				if (colorhashMap[tempNode] == colorhashMap[adj_node]) { return false; }
				if (!visited[adj_node]) {
					visited[adj_node] = true;
					bfs_queue.push(adj_node);
				}
			}
		}
		return true;
	}
};

int main() {
	int N, M;
	scanf("%d %d", &N, &M);
	gGraph colorMap(N);
	for (int i = 0; i < M; ++i) {
		int nx, ny;
		scanf("%d %d", &nx, &ny);
		colorMap.gInsert(nx, ny);
	}
	int K;
	scanf("%d", &K);
	for (int i = 0; i < K; ++i) {
		set<int> colorSet;
		for (int j = 0; j < N; ++j) {
			int ncolor;
			scanf("%d", &ncolor);
			colorhashMap[j] = ncolor;
			colorSet.insert(ncolor);
		}
		memset(colorMap.visited, 0, N);
		bool res = colorMap.BFS(0);
		if (res) {
			printf("%d-coloring\n", colorSet.size());
		}
		else {
			printf("No\n");
		}
	}

	system("PAUSE");
	return 0;
}

 

    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/alex1997222/article/details/86681654
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞