使用递归计算像素

时间:2017-11-01 20:28:45

标签: c arrays recursion

我有一个问题,我需要计算随机生成的2D数组中的1的数量。首先,用户通过命令行参数输入2D数组的大小,然后用户放入坐标以查看他放入的坐标中是否有1。如果坐标碰巧落在0,则认为否则如果输入的坐标落在1上,那么我应该递归地检查,右上,右下,右下,下,左下,左和左上。

我遇到的主要问题是我不知道我是否能从数组中读取一个1。我不知道将什么放入我的递归方法参数中。我有数组指针 xcoord ycoord ,这是用户输入的内容, col ,它们应该是命令行参数。

我认为其他一切都有效,但我可能错了。我试过这个递归公式。

if(arr[row][col] == 1)
{
     recursive(arr, xcoord-1, ycoord, row, col);
     blobsize = blobsize + 1;
     //more recursive things down here...
}

要检查,但它没有做任何事情。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <ctype.h>

int recursive(int **arr, int xcoord, int ycoord, int row, int col);//What are the arguments for the recursive function?

int main(int argc, char** argv)
{
    int i;//counters
    int j;//counters
    int xcoord;//x coordinate input
    int ycoord;//y coordinate input

    //random number generator thing idk lol
    srand((unsigned int)time(NULL));

    int row = strtol(argv[1], NULL, 0);//ROW from command line arguments (1st number)
    int col = strtol(argv[2], NULL, 0);//COL from command line arguments (2nd number)

    int *arrStorage = malloc(row * col * sizeof(int));//dynamically allocating memory for 2d array
    int **arr = malloc(row * sizeof(int*));       //pointer to pointer to array or whatever

    //intializing array
    for (i = 0; i < row; i++)
    {
            arr[i] = arrStorage + col * i;
    }

    //printing out 2d array
        for (i = 0; i <  row; i++)
        {
           for (j = 0; j < col; j++)
           {
              arr[i][j] = rand() % 2;
              printf("%d\t", arr[i][j]);
           }

           printf("\n");
        }

    printf(" ");

    //Exit the function when non number is entered
    //Otherwise continue
    while(1)
    {
        printf("Enter coordinate i,j (Non numeric to quit) \n");    

        if(1!=scanf("%d", &xcoord) || 1!=scanf("%d", &ycoord))
        {
            return 0;
        }

        printf("Blob size: %d\n", recursive(arr, xcoord, ycoord, row, col));
    }

    free(arr[0]);
    free(arr);

}

int recursive(int **arr, int xcoord, int ycoord, int row, int col)
{
    int blobsize = 0;

    //This is outside the bounds (BASE CASE)
    if(xcoord > row && ycoord > col)
    {
        return 0;
    }
    //If the selected xcoord & ycoord is 0
    if(arr[xcoord][ycoord] == 0)
    {
        return 0;
    }

    else
    {
        if((arr[xcoord][ycoord]==1))
        {
            //blobsize = blobsize + 1;
            //recursive(arr, xcoord - 1, ycoord, row, col);

        }
        else
        {

        }
    }

    return blobsize;

}

谢谢你能提供帮助

编辑:修复了一个关键部分。现在为了弄清楚递归部分而死。

1 个答案:

答案 0 :(得分:1)

OP正在打印一个随机数,但没有将数字分配给数组。

只需指定值然后打印即可。

// printf("%d\t", rand() % 2);
arr[i][j] = rand() % 2;
printf("%d\t", arr[i][j]);
相关问题