【发布时间】:2021-06-17 00:22:10
【问题描述】:
注意:我更喜欢c语言的算法或代码,提前谢谢。
假设我有一个 5x5 二维数组。
00, 00, 01, 01, 00
01, 00, 01, 01, 00
01, 00, 00, 01, 01
01, 01, 00, 00, 00
01, 00, 00, 01, 01
分组标准 :- 数组中上下左右或对角相连的所有1(01)都属于同一组。
现在,我想将所有 1 (01) 组合在一起而不进行递归,使我的数组看起来像:-
00, 00, 02, 02, 00
01, 00, 02, 02, 00
01, 00, 00, 02, 02
01, 01, 00, 00, 00
01, 00, 00, 03, 03
最后我输出有多少组。在这里,我输出 3。
假设我从一个索引位置找到连接,假设我在 i=1 和 j=0。 现在使用嵌套循环,我可以从我所在的位置找到所有连接。
for(int i=-1; i<2; i++){
for(int j=-1; j<2; j++){
}}
但是如何从连接中找到连接?假设我找到了 i=1, j=0 的所有连接。如果我在 i=1,j=1 找到 1,那么我该如何继续搜索?这里递归似乎很容易,但是没有递归我该怎么做呢?
这是我目前所拥有的。我没有时间限制,所以我这样做很愚蠢。
void printImgArray(int array[L][L])
{
printf("------ Image Contents -------\n");
int i, j;
for (i=0; i<L; i++)
{
for (j=0; j<L; j++)
printf("%02d, ",array[i][j]);
printf("\n");
}
printf("-----------------------------\n");
}
int checkIndex(int i, int j){
return i >= 0 && j>=0 && i< L && j< L;
}
int colorNonRecursively(int image[L][L]) {
int copyArray[L][L] = {0};
int i, j, new_i, new_j;
int counter = 1;
for(i=0; i<L; i++){
for(j=0; j<L; j++){
for(new_i=-1; new_i<2; new_i++){
for(new_j=-1; new_j<2; new_j++){
if(copyArray[i][j] != 1 && image[i][j] != 0){
copyArray[i][j] = 1;
image[i][j] = counter;
if(checkIndex(i+new_i, j+new_j)){
if(copyArray[i+new_i][j+new_j] != 1 &&
image[i+new_i][j+new_j] != 0){
copyArray[i+new_i][j+new_j] = 1;
image[i+new_i][j+new_j] = counter;
}
}
}
}
}
counter++;
}
}
int main(){
int cellImg[L][L]={{0,0,1,1,0},\
{1,0,1,1,0},\
{1,0,0,1,1},\
{1,1,0,0,0},\
{1,0,0,1,1}};
printImgArray(cellImg);
colorNonRecursively(cellImg);
printImgArray(cellImg);
return 0;
}
输入二维数组:-
00, 00, 01, 01, 00
01, 00, 01, 01, 00
01, 00, 00, 01, 01
01, 01, 00, 00, 00
01, 00, 00, 01, 01
输出二维数组:-
00, 00, 03, 04, 00
06, 00, 08, 09, 00
11, 00, 00, 14, 15
16, 17, 00, 00, 00
21, 00, 00, 24, 25
在这里我可以看到我的计数器放置在正确的位置,但分组没有正确完成。我知道这段代码的运行时间为 N^4,但在我的情况下这并不重要,所以请忽略它。 我怎样才能正确地分组这些,以便我有这个数组作为输出?
输出二维数组(应该是):-
00, 00, 02, 02, 00,
01, 00, 02, 02, 00,
01, 00, 00, 02, 02,
01, 01, 00, 00, 00,
01, 00, 00, 03, 03,
【问题讨论】:
-
您能详细解释一下分组是如何进行的吗?第一列中的
01怎么没有分组。我无法理解它。 -
01 表示 1。1 和 0 用 2 个数字表示。 0 = 00 和 1 = 01。因此,只要任何 1 在其右左上或对角线处有另一个 1,它就会被计入同一组。我们会重新检查每一个连接的人及其周围环境。
标签: c algorithm multidimensional-array