spiral matrix in c

1

I did an algorithm to generate a spiral matrix given the amount of rows and columns, but it does not work for all the matrices and I do not know very well what the error could be

#include <stdio.h>
int main (void)
{
    unsigned short fila, columna ;
    printf ("Ingresar cantidad de filas: \n");
    scanf("%hd", &fila);
    printf("Ingresar cantidad de columnas: \n");
    scanf("%hd", &columna);
    int matriz[fila][columna];
    void GenerarMatriz (unsigned short, unsigned short, int[][columna]);
    GenerarMatriz(fila,columna, matriz);
    return 0;
}

void GenerarMatriz (unsigned short fila, unsigned short columna, int matriz[][columna])
{
    unsigned short i, j, inicio, limitecolumna, limitefila, tope, x;
    inicio = 0; //desde donde comienza a llenarse
    limitecolumna = columna ;// donde comienza el desenso
    limitefila = fila;
    tope = fila * columna ;//hasta donde se llena, que es la cantidad de elementos
    x = 1; //valores dentro de la matriz
    i = 0 ;
    /*La matriz se llena con 4 for, dos para filas y dos para columnas.
    Los primeros dos for empiezan cargando la primera fila y la ultima      
    columna. Los otros dos cargan cargan desde la ultima fila hacia la 
    ultima columna. Los for no estan anidados, el while debe ejecutarse         
    hasta llenar la matriz*/

    while (x <= tope)
    {
        for(j = inicio; j < limitecolumna  ; j++ )
        {
        matriz[i][j] = x++;
        /*x++;*/
        }
        for(i = inicio + 1 ; i < limitefila  ; i++)
        {
        matriz[i][j-1]= x++;
        /*x++;*/
        }
        for (j = limitecolumna - 1 ; j > inicio ; j--)
        {
        matriz[i-1][j-1]= x++;
        /*x++;*/
        }
        for (i = limitefila - 1; i > inicio + 1 ; i--)
        {
        matriz[i-1][j]= x++;
        /*x++;*/
        }
        inicio++;
        limitecolumna --;
        limitefila--;
    }
    for (i =0 ; i < fila ; i++){
    printf("\n");
    for (j = 0; j < columna ; j++)
    printf("%i\t", matriz[i][j]);
    }
    }

for example for a 4x5 matrix this is the impression, which is correct but for a 3x4, this is the result

thanks in advance

    
asked by Bubblegum Crisis 20.08.2017 в 06:02
source

1 answer

2

The error occurs in the third for loop, the conditions that you have allow you to update the value of the coordinates (1,1) of the matrix, although those coordinates have already been updated in the first for loop, overwriting the value in that element.

A simple solution is to add an extra condition for the third for loop, which verifies that the row calculated by the first for loop is not overwritten, and that it could be left as follows:

for (j = limitecolumna - 1 ; j > inicio && i > inicio + 1; j--)
{
matriz[i-1][j-1]= x++;
/*x++;*/
}
    
answered by 20.08.2017 / 11:05
source