Заполните матрицу размером nxn по спирали от 1 до n². - PullRequest
0 голосов
/ 14 июля 2020

Я должен был заполнить матрицу nxn по спирали от 1 до n² с помощью функций, а затем распечатать ее результат, но я не знаю, почему мой код не работает, может кто-нибудь помочь, пожалуйста?

Принцип заключался в создании разных функций, каждая из которых заполняет матрицу в разные промежутки времени, а затем вызывает эти функции в основной программе, которая распечатывает их в спиральной матрице.


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

/* initializing the array and variables for the whole program*/
int A[5][5],top,bottom,left,right;

int FillRowForward(int A[5][5],int top,int left,int right,int z)
/*function that fills the top of the matrix from left to right*/
{   left = 0;
        for(top=left,right=0;right<=4;right++)
    {
        A[top][right]=z;
        z++;

    }
    return A[top][right];
}
int FillRowBackwards(int A[5][5],int bottom,int left,int right,int z)
/*fills the lower part from  right to left*/
{   bottom =4;

    for(left=bottom,right=4;right>=0;right--)
    {
        A[left][right-1]=A[left][right]+z;
    }
    return A[left][right-1];
}

int FillColumnDownward(int A[5][5],int top,int bottom,int left,int z)
/*fills the last column from top to bottom*/
{
    left=0;
 for(top=left,bottom=4;top<=4;top++)
    {
        A[top+1][bottom]= A[top][bottom]+z;
    }
    return A[top][bottom];
}
int FillColumnUpward(int A[5][5],int top,int bottom,int left, int z)
/*fills the first column from bottop to top*/
{
    left =0;
    for(bottom=left,top=0;bottom>=1;bottom--)
    {
         A[bottom-1][top]=A[bottom][top]+z
    }
    return A[bottom][top];
}

int main()
{
    int i,j,k=1;


    while(k<5*5){
    int FillRowForward(int A[5][5],int top,int left,int right,int k);
    top++;
    int FillColumnDownward(int A[5][5],int top,int bottom,int right,int k);
    right--;
    int FillRowBackwards(int A[5][5],int bottom,int left,int right,int k);
    bottom--;
    int FillColumnUpward(int A[5][5],int top,int bottom,int left,int k);
    }
//prints the matrix
    for(i=0;i<=4;i++)
        for(j=0;j<=4;j++)
            printf("%d",A[i][j]);


    return 0;
}

Ответы [ 2 ]

0 голосов
/ 14 июля 2020

У вас есть ряд проблем, например:

int FillRowForward(int A[5][5],int top,int left,int right,int k);

не является вызовом функции, и вы никогда не меняете k, т.е. у вас бесконечный l oop.

В этом решении для отслеживания текущего направления заполнения матрицы используется переменная direction.

#include <stdio.h>

#define ARRSIZE 10

int main()
{
    int A[ARRSIZE][ARRSIZE] = { 0 };
    int i=0, j=0;
    int direction = 0;

    for(int k = 1; k <= (ARRSIZE*ARRSIZE); ++k)
    {
        A[i][j] = k;
        
        switch (direction)
        {
            case 0 :  // Go rigth
                if (((j + 1) == ARRSIZE) || (A[i][j+1] != 0))
                {
                    // Switch direction
                    direction = 1;
                    ++i;
                }
                else
                {
                    ++j;
                }
                break;
            case 1 :  // Go down
                if (((i + 1) == ARRSIZE) || (A[i+1][j] != 0))
                {
                    // Switch direction
                    direction = 2;
                    --j;
                }
                else
                {
                    ++i;
                }
                break;
            case 2 :  // Go left
                if (((j - 1) == -1) || (A[i][j-1] != 0))
                {
                    // Switch direction
                    direction = 3;
                    --i;
                }
                else
                {
                    --j;
                }
                break;
            case 3 :  // Go up
                if (((i - 1) == -1) || (A[i-1][j] != 0))
                {
                    // Switch direction
                    direction = 0;
                    ++j;
                }
                else
                {
                    --i;
                }
                break;
        }
    }

    for(i=0; i<ARRSIZE; i++)
    {
        for(j=0; j<ARRSIZE; j++)
            printf("%4d",A[i][j]);
        printf("\n");
    }

    return 0;
}

Вывод:

   1   2   3   4   5   6   7   8   9  10
  36  37  38  39  40  41  42  43  44  11
  35  64  65  66  67  68  69  70  45  12
  34  63  84  85  86  87  88  71  46  13
  33  62  83  96  97  98  89  72  47  14
  32  61  82  95 100  99  90  73  48  15
  31  60  81  94  93  92  91  74  49  16
  30  59  80  79  78  77  76  75  50  17
  29  58  57  56  55  54  53  52  51  18
  28  27  26  25  24  23  22  21  20  19
0 голосов
/ 14 июля 2020

У вас здесь пара проблем:

  1. Я полагаю, что нет необходимости в глобальных переменных, поэтому вы можете определить все в функции main()

  2. Как уже отмечалось, «В main() вы только предоставляете объявления функций, а не вызываете их».

  3. У вас есть бесконечное l oop в main(), потому что вы никогда не увеличивали var k

  4. Старайтесь избегать использования чисел в своей функции, вместо этого используйте переменные или константы c. Нет разницы в таких небольших проектах, но в более крупных проектах их можно легко спутать, а также, если вы хотите изменить, вы должны изменить каждое значение, et c.

Ваши функции не делают то, что должны делать. Вы можете написать что-то вроде этого (я нашел свою старую программу и немного изменил ее):

#include <stdio.h>

void print_mat(int mat[][5], int m, int n)
{
    int i,j;

    for(i = 0; i < m; i++)
    {
        for(j = 0; j < n; j++)
        {
            printf("%d\t", mat[i][j]);
        }

        printf("\n\n");
    }

    printf("\n");
}

void spiral(int mat[][5], int m, int n)
{
    int i, k = 0, l = 0;
    int counter = 1;
    
    while(k < m && l < n)
    {
        for(i = l; i < n; i++)
        {
            mat[k][i] = counter++;
        }
        k++;

        for(i = k; i < m; i++)
        {
             mat[i][n-1] = counter++;
        }
        n--;

        if(k < m)
        {
            for(i = n-1; i >= l; i--)
            {
                mat[m-1][i] = counter++;
            }
            m--;
        }

        if(l < n)
        {
            for(i = m-1; i >= k; i--)
            {
                mat[i][l] = counter++;
            }
            l++;
        }
    }
}

int main()
{
    int mat[5][5];
    int n = 5;

    spiral(mat,n,n);
    
    print_mat(mat,n,n);
    
    return 0;
}

Поскольку вам нужно создавать разные функции, вы можете попробовать разделить эту spiral() функцию на несколько более мелких функций , это может быть хорошим упражнением.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...