计算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[ ]。
代码:
学习:
1、这里学习一下c语言如何静态和动态实现二维数组,如何将二维数组作为函数参数。
2、学习一下DFS思想的使用。
题目:给定一个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思想的使用。
相关文章推荐
- 给定数量的币值,如25分,10分,5分,1分,编写计算n分的有多少种表示方法
- 二维数组练习03_计算矩阵边缘元素之和
- 9.9递归和动态规划(八)——给定数量不限的硬币,币值为25分,10分,5分,1分,计算n分有几种表示法
- 稀疏矩阵A和B,其行数和列数对应相等,编写一个程序,计算A和B之和,假设稀疏矩阵采用三元组表示
- 二维数组计算4*4矩阵对角线上的元素之和
- 9.8 给定数量不限的硬币,25,10,5,1,编写代码计算n分有几种表示法。
- 换零钱:有数量不限的硬币,币值为25分、10分、5分和1分,请编写代码计算n分有几种表示法。
- 计算数组的二进制表示的01个数
- java第四周 任务四 用二维数组表示矩阵,实现矩阵乘法
- 9.9递归和动态规划(八)——给定数量不限的硬币,币值为25分,10分,5分,1分,计算n分有几种表示法
- 给定数量不限的硬币,币值为25分、10分、5分和1分,编写代码计算n分有多少种表示法。
- 有数量不限的硬币,币值为25分、10分、5分和1分,请编写代码计算n分有几种表示法
- 给定数量不限的硬币,币值为25分,10分,5分和1分,编写代码计算n分有几种表示法
- 第九周项目3 稀疏矩阵的三元组表示的实现1
- 如何计算一个有符号数的补码表示?
- 第9周实践项目3-稀疏矩阵的三元组表示的实现及应用.cp
- 矩阵、二维数组
- 第九周实践项目三---稀疏矩阵的三元组表示的实现及应用
- 1397 计算矩阵幂
- calc 计算 题解(矩阵乘法优化动态规划)