알고리즘/SWEA

[SWEA] 1954. 달팽이 숫자

Ellie67 2022. 11. 7. 23:24

https://swexpertacademy.com/main/main.do? 

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com

 

SWEA 1954번

 

DFS를 이용해서 풀었다.

기초중에 기초인데, DFS 사용을 어려워해서 걱정이다.

import java.util.Scanner;

public class P1954 {
    static int n;
    static int[][] a;
    static int[] dx={-1,0,1,0}, dy={0,1,0,-1};
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int T = sc.nextInt();
        for(int t=1; t<=T; t++) {
            n = sc.nextInt();
            a = new int[n][n];
            System.out.println("#"+t);
            solution(1, 0, 0, 0);
        }
    }
    public static void solution(int start,int x, int y, int dir){
        if(start==n*n){
            a[x][y] = start;
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    System.out.print(a[i][j] + " ");
                }
                System.out.println();
            }
        } else {
            a[x][y] = start;
            int nx = x + dx[dir];
            int ny = y + dy[dir];
            if(nx<0 || nx>=n || ny<0 || ny>=n || a[nx][ny]!=0){
                dir = (dir+1)%4;
            }
            x = x + dx[dir];
            y = y + dy[dir];
            solution(start+1, x, y, dir);
        }
    }
}