计算01矩阵中的0Group的数量 二维数组表示

本文介绍了一种使用深度优先搜索(DFS)算法解决特定矩阵中独立0群数量问题的方法,并提供了完整的C语言实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目源自于待字闺中的微信。

题目:给定一个n*n的board里面是0或1算出里面独立的0group的数量。比如

0 0 1 1 1
0 1 1 1 0
1 1 1 1 0
1 0 1 1 1
1 1 1 1 1

答案:3。


思路:虽然不是图,但是我仍然可以用图的DFS思想。我更没有必要用实现它对应的图。为了计数同时为了节省空间,把矩阵的元素本身来作为DFS时使用的标记量visited[ ]。


代码:

#include <stdio.h>
#include <malloc.h>
const int row = 5, col = 5;
//图的DFS,把所有连通结点标记为count
void DFS(int m[][col], int i, int j, int row, int col, int count)
{
	m[i][j] = count;
	if(i>0 && m[i-1][j] == 0)
	{
		DFS(m, i-1, j, row, col, count);
	}
	if(j>0 && m[i][j-1] == 0)
	{
		DFS(m, i, j-1, row, col, count);
	}
	if(i<row-1 && m[i+1][j] == 0)
	{
		DFS(m, i+1, j, row, col, count);
	}
	if(j<col-1 && m[i][j+1] == 0)
	{
		DFS(m, i, j+1, row, col, count);
	}
}

//对每个"为0且没有被标记"的结点进行DFS
int get_group(int m[][col],  int row, int col)
{
  int count = 1; //01都被占用了,所以从2起始吧
  for(int i=0;i<row;i++)
  {
    for(int j=0;j<col;j++)
    {
      if(m[i][j] == 0) 
	  {
		count++;
		DFS(m, i, j, row, col, count);  
	  }
    }
  }
  return count-1;//我是从2起始的
}

void display(int m[][5])
{
	for(int i=0;i<row;i++)
	{
		for(int j=0;j<col;j++)
			printf("%d ", m[i][j]);
		printf("\n");
	}

}
int main()
{
#if 0
  //手工输入矩阵的方式
  int (*m)[col] = (int (*)[col])malloc(sizeof(int)*row*col);
  for(int i=0;i<row;i++)
	  for(int j=0;j<col;j++)
		  scanf("%d",&m[i][j]);
#endif

#if 1
  //二维数组初始化的方式
  int m[][col] = {{0,0,1,1,1},
                  {0,1,1,1,0},
                  {1,1,0,1,0},
                  {1,0,1,0,0},
                  {1,0,0,0,1}};
#endif

  display(m);
  printf("%d\n", get_group(m, row, col));
  display(m);
  return 1;
}


学习:

1、这里学习一下c语言如何静态和动态实现二维数组,如何将二维数组作为函数参数。

2、学习一下DFS思想的使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值