C 无法执行连接的对象/孤岛程序

C 无法执行连接的对象/孤岛程序,c,C,我已经编写了一个程序,可以识别二维整数矩阵中的孤岛。孤岛是由1组成的集合,以这样的方式放置,每个1与周围8个单元中的至少另一个1相邻。该程序适用于任何数组,除非相关的1位于最后一行,并且搜索周围的1超出了数组的最后一行 这是我的密码 #include<stdio.h> #include<stdlib.h> void objectCount(int **arr, int row, int col, int i, int j) { *(*(arr+i)+j) = -1

我已经编写了一个程序,可以识别二维整数矩阵中的孤岛。孤岛是由1组成的集合,以这样的方式放置,每个1与周围8个单元中的至少另一个1相邻。该程序适用于任何数组,除非相关的1位于最后一行,并且搜索周围的1超出了数组的最后一行

这是我的密码

#include<stdio.h>
#include<stdlib.h>
void objectCount(int **arr, int row, int col, int i, int j)
{
    *(*(arr+i)+j) = -1; //Mark as visited
    int p,q;
    //Search for surrounding 8 cells
    for(p=i-1;p<=i+1;p++)
        for(q=j-1;q<=j+1;q++)
        {
            printf("\n\tTesting position %d,%d",p+1,q+1);
            //Condition to ensure search is within array boundaries, excluding the visited cell
            if((p!=i||q!=j) && !(p<0||q<0) && arr[p][q]==1 && (p<row && q<col))
            {
                printf("\n\t\tGoing to mark %d,%d",p+1,q+1);
                objectCount(arr,row,col,p,q); //Recursively call the function from the newly identified cell with 1
                printf("\n\t\tMarking %d,%d",p+1,q+1);
            }
            printf("\tTested position %d,%d",p+1,q+1);
        }
}
int islands(int **arr, int m, int n)
{
    int count=0,i,j;
    //Go through all the elements in the array
    for(i=0;i<m;i++)
        for(j=0;j<n;j++)
            if(*(*(arr+i)+j)==1)
            {
                count++;
                printf("\nGroup spotted at %d,%d",i+1,j+1);
                objectCount(arr,m,n,i,j); //To mark the entire island with -1
            }
    return count;
}
void main()
{
    int m,n,i,j;
    printf("Enter number of rows:\n");
    scanf("%d",&m);
    printf("Enter number of columns:\n");
    scanf("%d",&n);
    int **a = malloc((m+1)*sizeof(int *));
    printf("Enter the matrix:\n");
    for(i=0;i<m;i++)
    {
        *(a+i) = malloc(n*sizeof(int));
        for(j=0;j<n;j++)
            scanf("%d",(*(a+i)+j));
    }
    printf("Number of connected objects = %d",islands(a,m,n));
}
这是不同但相似输入的输出方式

Enter number of rows: 
3
Enter number of columns: 
4 
Enter the matrix: 
1 1 0 0
0 0 0 1
1 1 0 1
Number of connected objects = 3
添加了“测试位置”和“标记”行,以查看错误发生的位置。在处理最后一行时,程序不知何故陷入了if条件。任何关于如何发现问题并解决问题的想法

我已经在不同的网站上看到了其他的例子,比如Geeksforgeks,但是我想知道为什么这个程序不能运行。

由于以下原因,顺序很重要。如果你有一个If语句,比如

if(p<row && q<col)

必须避免超出
objectCount()
中的数组边界。在访问数组之前,需要进行边界检查;交换
arr[p][q]==1&&(p@ChrisTurner成功了!首先检查数组绑定如何改变任何事情?以前的安排在检出绑定列时效果很好。
if(p<row && q<col)
if((p!=i||q!=j) && p>=0 && q>=0 && p<row && q<col && arr[p][q]==1)