공 굴리기 질문드립니다.
미해결
자바 코딩테스트 - it 대기업 유제
이렇게 작성하니까 배열 범위가 벗어낫다고 하는데, 어디가 벗어나는지 잘 모르겠습니다. import java.awt.List; import java.util.*; class Node implements Comparable<Node>{ int x; int y; int c; Node(int x, int y, int c){ this.x=x; this.y=y; this.c=c; } @Override public int compareTo(Node o) { return this.c - o.c; } } class Main { public static int n,m; public static int INF = (int)1e9; public static int[][] cost; public static int[] dx = {0,0,1,-1}; public static int[] dy = {1,-1,0,0}; public int solution(int[][] board, int[] s, int[] e){ int answer; int n = board.length; int m = board[0].length; cost = new int[n][m]; for(int i = 0; i < n; i++) Arrays.fill(cost[i],INF); answer = dij(s[0],s[1],board,e[0],e[1]); if(answer == INF) return -1; else return answer; } public static int dij(int s,int e, int [][]board, int e1, int e2) { PriorityQueue<Node> q = new PriorityQueue<>(); q.offer(new Node(s,e,0)); cost[s][e] = board[s][e]; while(!q.isEmpty()) { Node tmp = q.poll(); int nowx = tmp.x; int nowy = tmp.y; int nowcnt = tmp.c; if(nowcnt>cost[nowx][nowy]) continue; for(int i=0; i<4; i++) { int nx = nowx; int ny = nowy; int len =nowcnt; while(nx>=0 && ny>=0 && nx<n && ny<m && board[nx][ny]==0) { nx+=dx[i]; ny+=dy[i]; len++; } nx-=dx[i]; ny-=dy[i]; len--; if(cost[nx][ny]>len) { cost[nx][ny] = len; q.offer(new Node(nx,ny,cost[nx][ny])); } } } return cost[e1][e2]; } public static void main(String[] args){ Main T = new Main(); System.out.println(T.solution(new int[][]{{0, 0, 1, 0, 0, 0}, {0, 0, 1, 0, 0, 0}, {0, 0, 0, 0, 1, 0}, {1, 0, 1, 1, 1, 0}, {1, 0, 0, 0, 0, 0}}, new int[]{1, 0}, new int[]{4, 5})); System.out.println(T.solution(new int[][]{{0, 0, 1, 0, 0, 0}, {0, 0, 1, 0, 0, 0}, {0, 0, 0, 0, 1, 0}, {1, 0, 1, 1, 1, 0}, {1, 0, 0, 0, 0, 0}}, new int[]{0, 0}, new int[]{4, 2})); System.out.println(T.solution(new int[][]{{1, 0, 1, 0, 0}, {0, 0, 0, 0, 0}, {0, 0, 0, 1, 0}, {1, 1, 0, 1, 1}, {0, 0, 0, 0, 0}}, new int[]{0, 3}, new int[]{4, 2})); System.out.println(T.solution(new int[][]{{0, 1, 0, 1, 0, 0}, {0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 1, 0}, {0, 1, 1, 0, 1, 1}, {0, 0, 0, 0, 0, 0}}, new int[]{0, 0}, new int[]{4, 5})); System.out.println(T.solution(new int[][]{{0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 1, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 1, 0, 0, 0}, {0, 0, 1, 0, 0, 0, 0, 0}}, new int[]{0, 0}, new int[]{4, 3})); } }
- java
- 코딩-테스트





