0

我正在尝试为二维数组中的 sipral 矩阵编写 ac 程序。哪个输出应该如下。我已经完成了矩阵输出的编码,但不能做螺旋矩阵的输出。我在我的程序中找不到错误。请帮忙

输出

给定矩阵:

3 6 3 8
4 7 1 9
3 8 2 7
5 2 9 8

螺旋遍历的输出:

3 6 3 8 9 7 8 9 2 5 3 4 7 1 2 8

代码

#include<stdio.h>
int main()
{
   int row = 0, //top most row
     b =row-1,  // bottom  row
     col= 0,    // left most column
     r = col-1, // right column
     size = 0,
     matrix[10][10],
     i;
    int dir;

printf("\n Size of Matrix: "); // enter the size of Matrix//
scanf("%d", &size); 

printf("\n  Enter Matrix Elements: \n");  // Enter Matrix Element//
for(row=0;row<size;row++)    // looping for enter row//
{
    for(col=0;col<size;col++)  // looping for enter column//
    {
        printf("    Element [%d][%d] :", row,col); // print output of element. say  Element[1][0]=  //
        scanf("%d" , &matrix[row][col]); // input matrix element //
    }
    printf("\n");
}

printf("\n the given Matrix is :\n"); // print output of given Matrix //

    for(row=0;row<size;row++) // looping for row//
    {
        for(col=0;col<size;col++) // looping for column//
        {
            printf("%4d",matrix[row][col]); //output of matrix//
        }
        printf("\n");
    }

    printf("output of helical traverse matrix is: \n");

    while(col<=r && row<=b) //condition exist if left column<= right column && Topmost row<= bottom row.I set four direction. dir =0 for left to right , dir=1 for top to bottom, dir 2 for right to left, dir 4 for bottom to top.//
    {
        if(dir==0){
            for(i=col;i<=r;i++){

                printf("%4d",matrix[row][i]); //print out 3 6 3 8//
            }
                row++;  //increase top row .so now 2 nd row become the top most row// 
            }

        else if(dir==1){
            for(i=row;i<=b;i++){      // looping for print output 9 7 8

                printf("%4d",matrix[i][col-1]); 
            }

                r--; //decrease left column. so now 2nd column from the right becomes the right most column//

        }
        else if(dir==2)
        {
            for(i=r;i>=col;i--){ //looping for print output of 9 2 5//

                printf("%4d",matrix[b][i]);
            }

                b--; //decerase bottom row. so now 2 nd row from bottom becomes the bottom row.//

        }
        else if(dir==3)
        {
            for(i=b;i>=row;i--){ //looping for print out 3 4//

                printf("%4d",matrix[i][col]);
            }
                col++; //icrease left column. so now 2nd column from left becomes left most column//

        }
        dir=(dir+1)%4;
    }



    return 0;
}
4

1 回答 1

0

需要重新设置变量。,

r=b=size-1;
col=row=0;
dir=0;
while(col<=r && row<=b)
{
...
     printf("%4d",matrix[i][b]);//printf("%4d",matrix[i][col-1]);
于 2014-05-21T19:48:57.870 回答