Fill 2d array in spiral order in c

前端 未结 1 1434
不思量自难忘°
不思量自难忘° 2021-01-29 05:53

I\'m doing program where I enter the number from keyboard. Then 2d array is created, and it\'s filled in spiral order till this number. All elements after the number will be equ

相关标签:
1条回答
  • 2021-01-29 06:35

    Try this:

    void printArray(int array[10][10], int m, int n) {
    
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                printf("%i\t", array[i][j]);
            }
            printf("\n");
        }
        printf("\n");
    }
    
    void spiral(int array[10][10], int m, int n, int s)
    {
        int size, b, x = 0, y = 1, num = 1;
        size = m*n;
        while ( num <= s )
        {
    
            for (b = x; b < n; b++)
            {
                if (num <= s) {
                    array[x][b] = num;
                    num++;
                } else array[x][b] = 0;
            }
    
            if (num == size + 1)
            {
                break;
            }
    
            for (b = y; b < m; b++)
            {
                if (num <= s) {
                    array[b][n - 1] = num;
                    num++;
                } else array[b][n - 1] = 0;
            }
    
            if (num == size + 1)
            {
                break;
            }
    
            y++;
            n--;
    
            for (b = n - 1; b > x; b--)
            {
                if (num <= s) {
                    array[m - 1][b] = num;
                    num++;
                } else array[m - 1][b] = 0;
            }
    
            if (num == size + 1)
            {
                break;
            }
    
    
            for (b = m - 1; b > x; b--)
            {
                if (num <= s) {
                    array[b][x] = num;
                    num++;
                } else array[b][x] = 0;
            }
            x++; 
            m--;
        }
    }
    
    
    
    int main()
    {
        int m, n, s, array[10][10];
        srand(time(NULL));
        m = 2 + rand() % 5;
        n = 2 + rand() % 5;
        memset(array, 0, sizeof(array[0][0]) * 10* 10);
        printf("enter the number \n");
        scanf("%i", &s);
        spiral(array, m, n, s);
    
        printArray(array, m, n);
    
    
        return (0);
    }
    

    Before you had some weird for loop on top of your spiral function. The num++ in it interfered with the fact that you already increased num by one and made it skip the number the next time it would write in the uppermost line. I changed it to a while loop that runs until num>s and it seems to work for me now.

    Note that I just added printArray for easier debugging.

    0 讨论(0)
提交回复
热议问题