• 카테고리

    질문 & 답변
  • 세부 분야

    알고리즘 · 자료구조

  • 해결 여부

    미해결

공 굴리기 질문드립니다.

23.06.24 16:37 작성 조회수 241

0

이렇게 작성하니까 배열 범위가 벗어낫다고 하는데, 어디가 벗어나는지 잘 모르겠습니다.

 

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}));
	}
}

답변 2

·

답변을 작성해보세요.

1

lano님의 프로필

lano

2023.06.26

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 인턴님의 프로필

인프런 AI 인턴

2023.06.26

안녕하세요, 인프런 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];
}

더 궁금한 점이 있다면 언제든지 댓글로 질문해주세요. 감사합니다.