SWEA 1954 달팽이 숫자

1 개요[ | ]

SWEA 1954 달팽이 숫자

2 C++[ | ]

#include <iostream>
using namespace std;
int main() {
    int T;
    scanf("%d", &T);
    int N;
    int a[12][12];
    for(int tc=1; tc<=T; tc++) {
        scanf("%d", &N);
        for(int i=1; i<=N; i++) {
            for(int j=1; j<=N; j++) a[i][j] = 0;
        }
        for(int i=0; i<=N+1; i++) {
            a[0][i] = -1;
            a[i][0] = -1;
            a[N+1][i] = -1;
            a[i][N+1] = -1;
        }
        int r=1, c=0, d=6;
        int square = N*N;
        for(int num=1; num<=square; num++) {
            // check & turn
            if( d==6 && a[r][c+1]!=0 ) d=2;
            if( d==2 && a[r+1][c]!=0 ) d=4;
            if( d==4 && a[r][c-1]!=0 ) d=8;
            if( d==8 && a[r-1][c]!=0 ) d=6;
            if( d==6 && a[r][c+1]!=0 ) d=2;
            if( d==2 && a[r+1][c]!=0 ) d=4;
            // go
            if( d==6 ) c++;
            else if( d==2 ) r++;
            else if( d==4 ) c--;
            else if( d==8 ) r--;
            a[r][c] = num;
        }
        printf("#%d\n", tc);
        for(int i=1; i<N+1; i++) {
            for(int j=1; j<N+1; j++) printf("%d ", a[i][j]);
            printf("\n");
        }
    }
}

3 Java[ | ]

import java.util.Scanner;
import java.util.Arrays;
class Solution {
    static int num, r, c;
    static String direction;
    static int ar, ac;
    static int a[][];
    static void turn() {
        switch( direction ) {
            case "right": direction="down"; return;
            case "down": direction="left"; return;
            case "left": direction="up"; return;
            case "up": direction="right"; return;
        }
    }
    static void move(int n) {
        for(int i=0; i<n; i++) {
            num++;
            switch( direction ) {
                case "right": c++; break;
                case "down": r++; break;
                case "left": c--; break;
                case "up": r--; break;
            }
            a[r][c] = num;
        }
    }
    public static void main(String args[]) {
        a = new int[10][10];
        Scanner sc = new Scanner(System.in);
        int T = sc.nextInt();
        for( int t=1; t<=T; t++) {
            int n = sc.nextInt();
            direction = "right";
            r = 0; c = 0; 
            num = 1; a[0][0] = 1;
            move( n-1 );
            for(int i=n-1; i>0; i--) {
                turn();
                move( i );
                turn();
                move( i );
            }
            System.out.format("#%d\n", t);
            for(int i=0; i<n; i++) {
                for(int j=0; j<n; j++) {
                    System.out.format("%d ", a[i][j]);
                }
                System.out.println();
            }
        }
    }   
}
문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}