Z字形扫描C语言算法实现

#include
#include
#define RIGHT 1
#define DOWN 2
#define LEFTDOWN 3
#define RIGHTUP 4

int main()
{
    int row,col;
    int n=0;
    int **array;
    scanf("%d",&n);
    if(n<1 || n>500)
    {
        return 0;
    }
    array=(int**)malloc(sizeof(int*)*(n+1));
    int i;
    for(i=1;i<=n;i++)
    {
        array[i]=(int*)malloc(sizeof(int)*(n+1));
    }
    for(row=1;row<=n;row++)
    {
        for(col=1;col<=n;col++)
        {
            scanf("%d",&array[row][col]);
            if(array[row][col]<0 || array[row][col]>1000)
            {
                return 0;
            }
        }
    }
    row=1;
    col=1;
    int direction=0;
    int *resultArray;
    resultArray=(int*)malloc(sizeof(int)*n*n);
    int a;
    resultArray[0]=array[row][col];
    for(a=1;aif(direction==0)
        {
            direction=RIGHT;
        }
        else if(direction==RIGHT)
        {
            if(row+1<=n && col-1>=1)
            {
                direction=LEFTDOWN;
            }
            else
            {
                direction=RIGHTUP;
            }
        }
        else if(direction==LEFTDOWN)
        {
            if(row+1<=n && col-1>=1)
            {
                direction=LEFTDOWN;
            }
            else if(row+1<=n)
            {
                direction=DOWN;
            }
            else
            {
                direction=RIGHT;
            }
        }
        else if(direction==RIGHTUP)
        {
            if(row-1>=1 && col+1<=n)
            {
                direction=RIGHTUP;
            }
            else if(col+1<=n)
            {
                direction=RIGHT;
            }
            else
            {
                direction=DOWN;
            }
        }
        else
        {
            if(row+1<=n && col-1>=1)
            {
                direction=LEFTDOWN;
            }
            else
            {
                direction=RIGHTUP;
            }
        }

        if(direction==RIGHT)
        {
            ++col;
        }
        else if(direction==DOWN)
        {
            ++row;
        }
        else if(direction==LEFTDOWN)
        {
            ++row;
            --col;
        }
        else
        {
            --row;
            ++col;
        }
        resultArray[a]=array[row][col];

    }
    for(a=0;aprintf("%d ",resultArray[a]);
    }
    free(resultArray);
    int j;
    for(j=1;j<=n;j++)
    {
        free(array[j]);
    }
    free(array);
    return 0;
}

你可能感兴趣的:(c,数组,算法)