【发布时间】:2021-12-30 17:11:44
【问题描述】:
我用递归技术编写了一个代码,但程序显示分段错误错误。我是否犯了任何算法错误或只是我的代码中的错误??
问题:
矩阵中有 R*C 个单元格,其中 R 是行数,C 是每行中的单元格数。每个细胞中可能有也可能没有果实。一个水果的存在用 1 表示,一个细胞中没有水果用 0 表示。水果可以是不同的类型,属于同一类型的所有水果都排列在相邻的单元格中(有八个相邻的单元格:左上、上、右上、左、右、左下、下、右下)。程序必须打印矩阵中水果组的数量。
边界条件: 2
Input:
3 5
1 0 0 0 1
0 1 0 1 1
1 0 0 0 1
Output:
2
Explanation:
The first group is indicated by the letter F,
F 0 0 0 1
0 F 0 1 1
F 0 0 0 1
The second group is indicated by the letter S,
1 0 0 0 S
0 1 0 S S
1 0 0 0 S
Input:
5 6
1 0 0 0 1 0
0 0 1 1 1 0
1 0 0 0 1 0
0 0 0 0 0 0
1 1 0 1 1 1
Output:
5
1 必须至少与组中的一个 1 相邻,才能被视为组的成员。
我的解决方案:
#include<stdio.h>
#include<stdlib.h>
int R, C, rtnval = 1;
int checkBoundary(int i, int j)
{
return (i>-1 && j>-1 && i<R && j<C);
}
void checkGroup(int arr[R][C],int i, int j)
{
if(arr[i][j]==1)
{
arr[i][j] = 0;
//top
if((checkBoundary(i-1,j)!=0) && arr[i-1][j]==1)
{
checkGroup(arr,i-1,j);
//return;
}
//top-left
if((checkBoundary(i-1,j-1)!=0) && arr[i-1][j-1]==1)
{
//arr[i-1
checkGroup(arr,i-1,j-1);
//return;
}
//top-right
if((checkBoundary(i-1,j+1)!=0) && arr[i-1][j+1]==1)
{
//arr[i-1
checkGroup(arr,i-1,j+1);
//return;
}
//bottom
if((checkBoundary(i+1,j)!=0) && arr[i+1][j]==1)
{
//arr[i+1
checkGroup(arr,i+1,j);
//return;
}
//bottom-left
if((checkBoundary(i+1,j-1)!=0) && arr[i+1][j-1]==1)
{
checkGroup(arr,i+1,j-1);
}
//bottom-right
if((checkBoundary(i+1,j+1)!=0) && arr[i+1][j+1]==1)
{
checkGroup(arr,i+1,j+1);
}
//left
if((checkBoundary(i,j-1)!=0) && arr[i][j-1]==1)
{
checkGroup(arr,i,j-1);
}
//right
if((checkBoundary(i,j+1)!=0) && arr[i][j+1]==1)
{
checkGroup(arr,i,j+1);
}
}
}
int main()
{
scanf("%d%d",&R,&C);
int arr[R][C];
for(int i=0;i<R;i++){
for(int j=0;j<C;j++)
{
scanf("%d",&arr[i][j]);
}
}
int group = 0;
for(int i=0;i<R;i++)
{
for(int j=0;j<C;j++)
{
if(arr[i][j]==1)
{
checkGroup(arr,i,j);
group++;
}
}
}
printf("%d",group);
}
我已尝试跟踪所有线索以找到任何 1 并将它们设为 0,这样它们就不会被误认为是其他相邻的 1。
【问题讨论】:
-
你能告诉我更多吗?我找不到你
-
我只是想确保每一步都在边界内
-
有什么办法可以减少这段代码的 if's 和你对 I, j 都是 0 的建议是什么?