J

[JAVA] Programmers ๋ฏธ๋กœ ํƒˆ์ถœ ๋ช…๋ น์–ด ๋ณธ๋ฌธ

๐Ÿ”‘ Problem Solving/๐Ÿซ Programmers

[JAVA] Programmers ๋ฏธ๋กœ ํƒˆ์ถœ ๋ช…๋ น์–ด

snowball๐Ÿฐ 2023. 5. 8. 13:57

ํ’€์ด ๋ฐฉ๋ฒ•

  1. PriorityQueue๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ String์ด ์‚ฌ์ „ ์ˆœ์œผ๋กœ ๊ณ„์† ์ •๋ ฌ๋˜๊ฒŒ ํ•œ๋‹ค.
  2. ๊ฐ€์ง€์น˜๊ธฐ๋ฅผ ํ•˜๋ฉด์„œ poll ๊ฐ’์„ ์กฐ์‚ฌํ• ์ง€ ๋ง์ง€ ๊ฒฐ์ •ํ•œ๋‹ค.
    1. ๋„์ฐฉ ์œ„์น˜์™€ ํ˜„์žฌ ์œ„์น˜ ๊ฑฐ๋ฆฌ๊ฐ€ ๋‚จ์€ ๊ฑฐ๋ฆฌ๋ณด๋‹ค ํฌ๋ฉด ์ ˆ๋Œ€ ๋„์ฐฉํ•  ์ˆ˜ ์—†๋‹ค.
    2. (ํ˜„์žฌ ์œ„์น˜์™€ ๋„์ฐฉ ์œ„์น˜ ์‚ฌ์ด ๊ฑฐ๋ฆฌ)์™€ ๋‚จ์€ ๊ฑฐ๋ฆฌ์˜ ํ™€์ง์€ ๊ฐ™์•„์•ผ ํ•œ๋‹ค.
import java.io.*;
import java.util.*;

class Solution {
    static class load{
        int x;
        int y;
        int time;
        String route;
        load(int x, int y, int time, String route){
            this.x = x; this.y = y; this.time = time; this.route = route;
        }
        public String toString(){
            return route;
        }
    }
    static int[] dx = {1, 0, 0, -1}, dy = {0, -1, 1, 0};
    public String solution(int n, int m, int x, int y, int r, int c, int k) {
        PriorityQueue<load> q = new PriorityQueue<>((o1, o2) -> o1.route.compareTo(o2.route));
        q.offer(new load(x-1, y-1, 0, ""));
        boolean[][] v = new boolean[n][m];
        v[x-1][y-1] = true;
        while(!q.isEmpty()){
            load now = q.poll();
            if(now.x == r-1 && now.y == c-1 && now.time == k) return now.route;
            if(now.time > k) continue;
            if(!ispossible(now.x, now.y, r-1, c-1, k-now.time)) continue;
            for(int d=0; d<4; d++){
                int nx = now.x+dx[d];
                int ny = now.y+dy[d];
                if(nx < 0 || ny < 0 || nx >= n || ny >= m) continue;
                String Nroute = "";
                if(d == 0) Nroute = now.route+"d";
                else if(d == 1) Nroute = now.route+"l";
                else if(d == 2) Nroute = now.route+"r";
                else Nroute = now.route+"u";
                q.offer(new load(nx, ny, now.time+1, Nroute));
            }
        }
        return "impossible";
    }
    boolean ispossible(int x, int y, int r, int c, int time){
        int rest = Math.abs(r-x)+Math.abs(c-y);
        if(rest > time) return false;
        if((rest % 2) - (time % 2) == 0) return true;
        return false;
    }
}
Comments