Search code examples
cpointersmallocspiral

Spiral matrix(as 2d pointer)


I have a matrix (2d pointer, (**a)) and i want to scan the elements spiral-like.(first rown then last column,last line(reversed),first column,second line, so on. Ex:

1 2 3
8 9 4
7 6 5

i have the following code in C but i know im wrong in the "else" condition .

#include <stdio.h>
#include <malloc.h>

int main(void)
{
int i, j, n, m, p, q, **a, s, c = 0;
printf("rows\n");
scanf("%d", &m);
printf("cols\n");
scanf("%d", &n);
a = (int**)malloc(m*sizeof(int));
for (i = 0; i < m; i++)
{
    a[i] = (int*)malloc(n*sizeof(int));
}
printf("insert\n");
for (i = 0; i < m; i++)
{
    if (i % 2 == 0)
    {
        for (j = 0; j < n; j++)
        {
            printf("a[%d][%d]=", i + 1, j + 1);
            scanf("%d", &a[i][j]);
        }
    }
    else
    {
        for (j = i+1; j < m-i;j++)
        {
            scanf("%d", a[j][m-c]);
        }
        c++;
    }
}


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

Solution

  • A possible way could be using a variable direction, which could be either east, south, west, north. Denoting them by 0-3, now we proceed.

    Also, we use two auxiliary arrays,

    int xDir = [0, 1, 0, -1];
    int yDir = [1, 0, -1, 0];
    

    Starting with direction = 0. Every time you are done traversing in a certain direction, you will set direction = (direction + 1) % 4.

    We will also use another variable length, which will denote how far in a certain direction I should travel. Initially length = row size of your matrix.

    The value of length will be like row, col - 1, row - 1, col - 2, row - 2, col - 3..., and this pattern will continue.

    When you are done traversing the first row, set direction to 1, and update length to the next value of the pattern mentioned above. How you will know you're done? When length step has been completed.

    You stop when length value is 0 to begin with.

    How you take the next step?

    If your current position is (x,y), your next position will be (x + xDir[direction], y + yDir[direction]).

    For starter, I guess it would help you correct your procedure.