博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
BFS——求矩阵中“块”的个数
阅读量:4216 次
发布时间:2019-05-26

本文共 1134 字,大约阅读时间需要 3 分钟。

在这里插入图片描述

#include
#include
using namespace std;const int maxn = 100;struct node{
int x, y;}Node;int n, m; int matrix[maxn][maxn]; // 01矩阵 bool inq[maxn][maxn] = {
false};int X[4] = {
0, 0, 1, -1};int Y[4] = {
1, -1, 0, 0}; // 增量数组bool judge(int x, int y){
if(x >= n || x < 0 || y >= m || y < 0) return false; if(matrix[x][y] == 0 || inq[x][y] == true) return false; return true; } void BFS(int x, int y){
queue
Q; Node.x = x, Node.y = y; Q.push(Node); inq[x][y] = true; while(!Q.empty()) {
node top = Q.front(); Q.pop(); for(int i = 0; i < 4; i++) {
int newX = top.x + X[i]; int newY = top.y + Y[i]; if(judge(newX, newY)) {
Node.x = newX; Node.y = newY; Q.push(Node); inq[newX][newY] = true; } } }}int main(){
scanf("%d%d", &n, &m); for(int x = 0; x < n; x++) {
for(int y = 0; y < m; y++) {
scanf("%d", &matrix[x][y]); } } int ans = 0; for(int x = 0; x < n; x++) {
for(int y = 0; y < m; y++) {
if(matrix[x][y] == 1 && inq[x][y] == false) {
ans++; BFS(x, y); } } } printf("%d", ans); return 0;}

在这里插入图片描述

转载地址:http://ihtmi.baihongyu.com/

你可能感兴趣的文章
Android编译系统简要介绍和学习计划
查看>>
Android编译系统环境初始化过程分析
查看>>
user2eng 笔记
查看>>
DRM in Android
查看>>
ARC MRC 变换
查看>>
Swift cell的自适应高度
查看>>
【linux】.fuse_hiddenXXXX 文件是如何生成的?
查看>>
【LKM】整合多个LKM为1个
查看>>
【Windows C++】调用powershell上传指定目录下所有文件
查看>>
Java图形界面中单选按钮JRadioButton和按钮Button事件处理
查看>>
小练习 - 排序:冒泡、选择、快排
查看>>
SparkStreaming 如何保证消费Kafka的数据不丢失不重复
查看>>
Spark Shuffle及其调优
查看>>
数据仓库分层
查看>>
常见数据结构-TrieTree/线段树/TreeSet
查看>>
Hive数据倾斜
查看>>
TopK问题
查看>>
HQL排查数据倾斜
查看>>
DAG以及任务调度
查看>>
LeetCode——DFS
查看>>