• Home
  • About
    • Ryureka Moment photo

      Ryureka

      Sin Prisa, Sin Pausa

    • About Me
    • Facebook
    • Github
    • Youtube
  • Projects
  • Posts
    • Posts
    • ProblemSolvings
    • Tags
    • Blog
    • Examples
  • ProblemSolving
    • ProblemSolving
    • BOJ
    • Programmers
    • SWEA
    • LeetCode
  • FrontEnd
    • FrontEnd
    • HTML
  • BackEnd
    • BackEnd
    • Server
      • Server
      • Spring
      • NodeJS
    • DataBase
      • DataBase
      • MySQL
      • MongoDB
  • Programming
    • Programming
    • Java
    • JS
    • Python
    • CleanCode
  • ComputerScience
    • DataStructure
    • Algorithm

[BOJ] 1913. 달팽이

15 Apr 2026

Reading time ~1 minute

  • 풀이

풀이

(1,1) 위치에 N*N을 저장하고 1씩 감소시키면서 dir 방향을 하 우 상 좌로 변경시켜 가면서 숫자를 저장한다.

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		int M = sc.nextInt();
		int arr[][]=new int[N][N];
		int dx[] = {0,1,0,-1}; // 하, 우, 상, 좌
		int dy[] = {1,0,-1,0};
		int dir = 0; // 0:하, 1:우, 2:상, 3:좌
		int now_x = 0; // 현재 x좌표
		int now_y = 0; // 현재 y좌표
		int now_num = N*N; // 현재 숫자
		
		while(now_num > 0) {
			arr[now_y][now_x] = now_num; // 현재 좌표에 현재 값을 대입.
			int next_x = now_x + dx[dir]; // 다음 번의 예상 x좌표 구함.
			int next_y = now_y + dy[dir]; // 다음 번의 예상 y좌표 구함.
			// 다음 번의 x,y좌표가 벗어나거나 이미 들어있다면 방향을 변경. 
			if(next_x < 0 || next_x >= N || next_y < 0 || next_y >= N || arr[next_y][next_x] != 0) {
				dir = (dir + 1) % 4;
			}
			// 진행방향이 확정으므로 다음 위치를 현재 위치로 지정하고 다음 숫자도 1만큼 감소시킴.
			now_y = now_y + dy[dir];
			now_x = now_x + dx[dir];
			now_num = now_num - 1;			
		}
		
		// 달팽이 배열 출력.
		for (int i = 0; i < N; i++) {
			for (int j = 0; j < N; j++) {
//				if(arr[i][j]/10 == 0) System.out.print(" ");
				System.out.print(arr[i][j]+" ");
			}
			System.out.println();
		}
		
		// 숫자 M의 좌표 출력.
		for (int i = 0; i < N; i++) {
			for (int j = 0; j < N; j++) {
				if(arr[i][j]==M) {
					System.out.print((i+1)+" "+(j+1));
					break;
				}
			}
		}
		
	}
}


구현 Share