笔试题30——给无向图中节点绘色,使其满足相邻节点颜色不同

题目描述:
给一无向图中各个节点绘色,一共只有两种颜色,使其满足相邻节点颜色不同,并输出其中一种颜色的节点个数及序号;如果不满足,则输出-1。
示例:
第一行输入节点个数V和边数E,第二行输入E条边(每条边对应的两个节点),例如:
7 9
1 2 1 4 2 3 3 4 2 5 4 5 2 6 5 7 6 7
例图:
在这里插入图片描述
思路:
从节点1出发,首先入队列,进行广度优先搜索,依次判断当前节点的相邻节点颜色是否符合要求,如不满足要求,结束搜索,如满足要求,最后统计输出其中一种颜色的节点数目及序号。
核心代码如下:

#include <iostream>
#include <vector>
#include <deque>
using namespace std;

int a[1001][1001] = { 0 };
int color[1001][2] = { 0 };
int num[1001]; 
int num1 = 0;

int main() {
	//7 9
	//1 2 1 4 2 3 3 4 2 5 4 5 2 6 5 7 6 7
	int v, e, x, y;
	cin >> v >> e; //输入节点数和边数
	for (int i = 0; i < e; i++) { 
		cin >> x >> y; //输入e条边每条边对应的节点序号
		a[x][y] = 1;
		a[y][x] = 1;
	}
	deque<int> deq;
	deq.push_back(1);
	bool flag = false;
	while (!deq.empty()) {
		int cur = deq.front();  //cur存储当前所取节点的序号
		deq.pop_front(); //将该节点出队列
		int tmp = color[cur][0]; //tmp为该节点的颜色
		color[cur][1] = 2; //将该节点状态置为2(代表已设置颜色)
		for (int j = 1; j <= v; j++) { //寻找与cur相连的节点
			if (a[cur][j] == 1 && color[j][1] == 0) {  //j节点与cur节点之间有边,且颜色未被设置
				color[j][0] = 1 - tmp; //颜色取反
				color[j][1] = 2; //设置节点状态
				deq.push_back(j); //将该节点入队列
			}
			if (a[cur][j] == 1 && color[j][1] == 2) { //如果节点j颜色已被设置,判断颜色是否与tmp一致
				if (color[j][0] != (1 - tmp)) { //不一致
					flag = true;
					break;
				}
			}
		}
		if (flag) {
			num1 = -1;
			break;
		}
	}
	if (!flag) {
		num1 = 0;
		for (int k = 1; k <= v; k++) {
			if (color[k][0] == 1) 
				num[num1++] = k;
		}
	}

	cout << "#:" << num1;
	for (int d = 0; d < num1; d++) {
		cout << " " << num[d];
	}
	cout << endl;
	return 0;
}

运行结果:
在这里插入图片描述

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在C++的OpenCV,可以使用连通组件标记函数connectedComponentsWithStats()来获取图像的连通组件信息,并使用不同颜色绘制出每个连通组件。 下面是一个示例代码,演示了如何使用连通组件标记函数和绘制函数来实现连通组件绘色: ```cpp #include <opencv2/opencv.hpp> using namespace cv; int main() { // 读取图像 Mat image = imread("input.jpg", IMREAD_GRAYSCALE); // 进行连通组件标记 Mat labels, stats, centroids; int num_labels = connectedComponentsWithStats(image, labels, stats, centroids); // 创建一个彩色图像,用于绘制连通组件 Mat colored_image; cvtColor(image, colored_image, COLOR_GRAY2BGR); // 随机生成颜色 RNG rng(0); vector<Vec3b> colors(num_labels); for (int i = 0; i < num_labels; i++) { colors[i] = Vec3b(rng.uniform(0, 256), rng.uniform(0, 256), rng.uniform(0, 256)); } // 绘制连通组件 for (int y = 0; y < image.rows; y++) { for (int x = 0; x < image.cols; x++) { int label = labels.at<int>(y, x); if (label > 0) { colored_image.at<Vec3b>(y, x) = colors[label]; } } } // 显示结果图像 imshow("Connected Components", colored_image); waitKey(0); return 0; } ``` 这段代码首先读取了一张灰度图像,然后使用connectedComponentsWithStats()函数进行连通组件标记,得到每个连通组件的标签。接下来,创建一个彩色图像,用于绘制连通组件。然后,随机生成颜色,并根据每个像素的标签将对应的颜色绘制到彩色图像上。最后,显示结果图像。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值