(역)달뱅이 알고리즘

2011. 5. 24. 16:45머리쓰기/간단한 문제들




달팽이 알고리즘은

input : 5

 1  2  3  4  5

16 17 18 19 6

15 24 25 20 7

14 23 22 21 8

13 12 11 10 9

 

        int a[100][100] = {0,},i,j,prt_n,n,num=1;     

int Row=0,Column=-1,direct=1;       //Row는 행, Column는 열, direct는 방향


printf("입력 : ");

scanf("%d",&n);

prt_n=n;            //n을 따로 저장

while(n!=0)                      

{

for(i=0;i< n;i++)            // 가로 처리 반복문

{

Column+=direct;

a[Row][Column]=num++;

}

n--;

for(i=0;i< n;i++)           // 세로 처리 반복문

{

Row+=direct;

a[Row][Column]=num++;

}

direct*=-1;               // 방향결정부분

}


for(i=0;i<prt_n;i++)         // 출력

{

for(j=0;j<prt_n;j++)

printf("%3d",a[i][j]);

printf("\n");

}


유사하게 

input : 5


  1 16 15 14 13

  2 17 24 23 12

  3 18 25 22 11

  4 19 20 21 10

  5  6  7  8  9


    int a[100][100] = {0,};
    int n =0;
    cin >> n;
    int prt_n = n;
    int row=-1, column=0, direct=1;
    int num=1;

    if(n<= 10)

    {
        while(n!=0)
        {
            // column
            for(int i=0; i<n; i++)
            {
                row += direct;
                a[row][column]=num++;
            }
            n--;
            // row
            for(int i=0; i<n; i++)
            {
                column += direct;
                a[row][column]=num++;
            }
            direct*=-1;
        }
    }

    for(int i=0;i<prt_n;i++)         // 출력

    {
        for(int j=0;j<prt_n;j++)
            printf("%3d",a[i][j]);
        printf("\n");
    }





문제는 달팽이 알고리즘을 역으로

가운데에서부터

 

5를 입력시

 

21  22  23  24  25

20   7   8   9   10

19   6   1   2  11

18   5   4   3  12

17  16 15  14  13           

 

 



'머리쓰기 > 간단한 문제들' 카테고리의 다른 글

CodingTest_369_Game  (0) 2018.04.25
히스토그램 그리기.  (0) 2011.07.08
For문을 이용(3)  (0) 2011.05.24
문자열관련.  (0) 2011.05.24
For문을 이용(2)  (0) 2011.05.24