您的位置:首页 > 其它

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

2013-10-16 16:45 225 查看
题目源自于待字闺中的微信。

题目:给定一个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思想的使用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐