공 굴리기 질문드립니다.
428
27 câu hỏi đã được viết
이렇게 작성하니까 배열 범위가 벗어낫다고 하는데, 어디가 벗어나는지 잘 모르겠습니다.
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}));
}
}
Câu trả lời 2
1
public static int n,m;
int n = board.length;
int m = board[0].length;
-------------------------------------------------------------
위 부분이 잘못된 거 같습니다.
n,m 값을 static 변수로 선언을 하시고
solution() 메서드에서는 지역변수로 n,m을 선언및 초기화 하셔서
while(nx>=0 && ny>=0 && nx<n && ny<m && board[nx][ny]==0)
이 조건에서 사용하시는 static변수 n,m 에는 아무런 값이 할당되지 않아서 조건이 돌지 못하고
나오게 됩니다.
solution 메서드에서 n,m에 값을 초기화만 해주세요
0
안녕하세요, 인프런 AI 인턴이에요.
에러 메시지에 보면 “배열 범위가 벗어났다”고 나온다면, 코드에서 배열을 인덱스로 참조할 때 해당 인덱스가 배열의 범위를 초과한다는 뜻입니다. 보시면, nowx, nowy값이 변할 때마다 board배열을 참조하고 있는데, nx>=0 && ny>=0 && nx<n && ny<m의 조건문으로 범위를 검사한 이후에 참조를 하도록 코드가 작성되어야 합니다.
그러므로, 33번째 줄을 아래와 같이 변경해 주세요.
while(nx>=0 && ny>=0 && nx<n && ny<m && board[nx][ny]==0) {
...
}
그리고, 반복문 안에서 nx, ny, len 세 변수를 모두 변경하기 때문에 지역 변수로 선언하면 결과적으로 기존 변수 값이 유지되지 않게 됩니다. 따라서, 반복문 안에서 nx, ny, len을 사용하는 위치에서는 nowx, nowy, nowcnt값을 사용하는 것이 맞습니다.
위 내용들을 고쳐주시면 에러가 해결될 것 같습니다.
수정된 코드 예시입니다.
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 + dx[i];
int ny = nowy + dy[i];
int len = nowcnt;
while (nx >= 0 && ny >= 0 && nx < n && ny < m && board[nx][ny] == 0) {
len++;
nx += dx[i];
ny += dy[i];
}
if (cost[nx - dx[i]][ny - dy[i]] > len) {
cost[nx - dx[i]][ny - dy[i]] = len;
q.add(new Node(nx - dx[i], ny - dy[i], len));
}
}
}
return cost[e1][e2];
}
더 궁금한 점이 있다면 언제든지 댓글로 질문해주세요. 감사합니다.
비밀번호
0
65
1
과일 가져가기 이러한 경우에는 반례가 생기지 않나요?
0
161
2
cpu 스케줄링
0
105
2
외부 문제 질문
0
122
2
가장 많이 사용된 회의실
0
117
2
심사위원 문제 시간복잡도 질문
0
127
1
현관문 출입순서
0
96
1
미로의 최단거리 통로
0
74
1
집으로 이동 문제 코드
0
124
1
채점 사이트 개설
0
161
2
송아지를 잡자
1
110
1
다익스트라 + 환승횟수
0
135
2
문제풀이 해설 질문입니다.
0
124
2
"이동 횟수" 문제가 변형된다면?
0
155
2
예제 3번의 정답이 이해가 되지 않아요 선생님 ㅜㅜ
0
248
1
"비밀번호" 문제 확인 부탁드립니다!
0
170
1
최대 길이 연속수열 질문
0
192
1
잃어버린 강아지 문제 count 관련 질문있습니다
0
202
1
바둑대회 질문입니당
0
221
1
5. "최대 길이 바이토닉 수열" 에서 설명해주신 방법과 제가 직접 구현한 방법이 달라, 확인 한번 부탁드립니다
0
310
1
알파코드 풀이질문입니다
0
217
1
7번 비밀 번호 문제에 시간복잡도가 궁금합니다!
0
163
1
혹시 이렇게 작성해도 괜찮나요?
0
285
2
문제풀이 확인 부탁드립니다.
0
244
1

