螺旋矩阵(作为二维指针)

Spiral matrix(as 2d pointer)

我有一个矩阵(二维指针,(**a)),我想扫描螺旋状的元素。(第一行然后最后一列,最后一行(反转),第一列,第二行,所以在。 例如:

1 2 3
8 9 4
7 6 5

我在 C 中有以下代码,但我知道我在 "else" 条件下错了。

#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");
     }
   }

一种可能的方法是使用变量 direction,它可以是东、南、西、北。用0-3表示它们,现在我们继续。

另外,我们使用两个辅助数组,

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

direction = 0 开始。每完成一个方向的遍历,就会设置direction = (direction + 1) % 4.

我们还将使用另一个变量length,它表示我应该在某个方向上行驶多远。最初 length = row size of your matrix.

length 的值会像row, col - 1, row - 1, col - 2, row - 2, col - 3...,这种模式会继续下去。

当您完成第一行的遍历后,将 direction 设置为 1,并将长度更新为上述模式的下一个值。你怎么知道你已经完成了?当长度步长完成时。

当长度值为 0 时停止。

下一步你会怎么做?

如果您当前的位置是 (x,y),您的下一个位置将是 (x + xDir[direction], y + yDir[direction])

首先,我想它会帮助您更正程序。