백준 1913 달팽이 (Java,자바)

이번에 풀어본 문제는
백준 1913번 달팽이 입니다.

📕 문제 링크

❗️코드

import java.io.*;
import java.util.LinkedList;
import java.util.Queue;

class Point
{
    int x;
    int y;
    int val;
    int dir;
    int mv_cnt;
    int cnt;
    int curve_cnt;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public Point(int x, int y, int val,int dir, int mv_cnt, int cnt, int curve_cnt) {
        this.x = x;
        this.y = y;
        this.val = val;
        this.dir = dir;
        this.mv_cnt = mv_cnt;
        this.cnt = cnt;
        this.curve_cnt = curve_cnt;
    }
}
public class Main {
    static int N;
    static int [][] map;
    static int [] dx = {-1,0,1,0};
    static int [] dy = {0,1,0,-1};
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        N = Integer.parseInt(br.readLine());
        map = new int[N][N];
        int M = Integer.parseInt(br.readLine());

        Point answer = new Point(0,0);
        Queue<Point> q = new LinkedList<>();
        q.add(new Point(N/2,N/2,1,0,1,0,0));
        int end = N*N;

        while(!q.isEmpty())
        {
            Point snail = q.poll();

            int dir = snail.dir;
            int val = snail.val;
            int cur_mv_cnt = snail.mv_cnt;
            int cur_cnt = snail.cnt;
            int cur_curve_cnt = snail.curve_cnt;

            if(val == M)
            {
                answer = new Point(snail.x,snail.y);
            }
            map[snail.x][snail.y] = val;
            if(val == end) break;

            if(cur_curve_cnt == 2)
            {
                cur_mv_cnt++;
                cur_curve_cnt = 0;
            }
            if(cur_mv_cnt == cur_cnt)
            {
                dir = (dir + 1) % 4;
                cur_curve_cnt++;
                cur_cnt = 0;
            }

            int mx = snail.x + dx[dir];
            int my = snail.y + dy[dir];
            q.add(new Point(mx,my,val+1,dir,cur_mv_cnt,cur_cnt+1,cur_curve_cnt));
        }

        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        for(int [] i : map)
        {
            for(int j : i) bw.write(j+" ");
            bw.write("\n");
        }
        bw.write((answer.x+1)+" "+(answer.y+1));
        bw.flush();
        bw.close();
    }

    static boolean isValid(int x, int y)
    {
        return x >= 0 && y >= 0 && x < N && y < N;
    }
}

📝 풀이

구현 문제입니다.
달팽이가 규칙적으로 회전하며 나아가는데, 직진횟수는 2번 회전할때마다 1칸씩 증가합니다.
먼저 직진횟수를 1칸으로 시작하여, 직진 횟수를 채웠다면 달팽이가 회전합니다. 예를들어, 시작과 동시에 달팽이가 1칸 이동했다면 현재 직진횟수는 1칸 이므로 회전합니다. 직진 횟수가 2칸일 때는, 달팽이가 2칸 전진한 후 회전합니다. 직진횟수가 3칸 일때는 달팽이가 3칸 전진한 후 회전합니다.
위 과정을 진행하면서, 만약 달팽이가 회전한 횟수가 2회가 되었다면, 직진 횟수를 1증가시켜주는 조건을 추가하면 결과 배열을 만들어낼 수 있습니다.

📜 후기

규칙을 찾았지만 그걸 구현하기 너무 머리가 아팠던 문제입니다..
이 규칙이 정답인지는 모르겠으나, 다시봐도 굉장히 복잡해보이는 코드네요ㅠㅠ 제가 사실 배열 회전이나, 이 같은 배열내에서 규칙적으로 이동하는? 문제들을 되게 복잡하고 어려워 하는데요.... 고통스럽지만 자꾸 부딪혀서 풀어봐야겠습니다 ㅠㅠ

좋은 웹페이지 즐겨찾기