• 카테고리

    질문 & 답변
  • 세부 분야

    알고리즘 · 자료구조

  • 해결 여부

    미해결

방향바꾸기 문제 질문드립니다.

23.11.27 23:07 작성 조회수 176

0

import java.io.*;
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 int solution(int[][] board) {
	        int answer = 0;
	        
	        int n=board.length;
	        int m=board[0].length;
	        
	        int[][] dist =new int[n][m];
	        int INF = (int)1e9;
	        PriorityQueue<Node> q = new PriorityQueue<>();
	        q.add(new Node(0,0,0));
	        for(int i=0; i<n; i++) Arrays.fill(dist[i], INF);
	        dist[0][0]=0;
	        
	        int[] dx = {0,0,1,-1};
	        int[] dy = {1,-1,0,0};
	        
	        while(!q.isEmpty()) {
	        	Node tmp = q.poll();
	        	int nowx = tmp.x;
	        	int nowy = tmp.y;
	        	int nowc=tmp.c;
	        	int dir = board[nowx][nowy]-1;
	        	if(nowc>dist[nowx][nowy]) continue;
	        	
	        	for(int i=0; i<4;i++) {
	        		int nx = nowx+dx[i];
	        		int ny = nowy+dy[i];
	        		
	        		if(i==dir && dist[nx][ny]>nowc) {
	        			dist[nx][ny] = nowc;
	        			if(q.add(new Node(nx,ny,dist[nx][ny])));
	        		}
	        		else if(i!=dir && dist[nx][ny]>nowc+1) {
	        			dist[nx][ny] = nowc+1;
	        			q.add(new Node(nx,ny,dist[nx][ny]));
	        		}
	        	}
	        }
	        answer = dist[n-1][m-1];
	        return answer;
	    }

		public static void main(String[] args){
			Main T = new Main();
			System.out.println(T.solution(new int[][]{{3, 1, 3}, {1, 4, 2}, {4, 2, 3}}));
			System.out.println(T.solution(new int[][]{{3, 2, 1, 3}, {1, 1, 4, 2}, {3, 4, 2, 1}, {1, 2, 2, 4}}));
			System.out.println(T.solution(new int[][]{{3, 2, 1, 3, 1, 2}, {2, 1, 1, 1, 4, 2}, {2, 2, 2, 1, 2, 2}, {1, 3, 3, 4, 4, 4}, {1, 2, 2, 3, 3, 4}}));
			System.out.println(T.solution(new int[][]{{3, 2, 1, 3, 1, 2, 2, 2}, {2, 1, 1, 1, 4, 2, 1, 1}, {2, 2, 2, 1, 2, 2, 3, 4}, {1, 3, 3, 4, 4, 4, 3, 1}, {1, 2, 2, 3, 3, 4, 3, 4}, {1, 2, 2, 3, 3, 1, 1, 1}}));
			System.out.println(T.solution(new int[][]{{1, 2, 3, 2, 1, 3, 1, 2, 2, 2}, {1, 2, 2, 1, 1, 1, 4, 2, 1, 1}, {3, 2, 2, 2, 2, 1, 2, 2, 3, 4}, {3, 3, 1, 3, 3, 4, 4, 4, 3, 1}, {1, 1, 1, 2, 2, 3, 3, 4, 3, 4}, {1, 1, 1, 2, 2, 3, 3, 1, 1, 1}}));
		}
	 }

이렇게 작성하니까 배열 길이가 맞지 않다고 뜹니다.

어디가 잘 못된건가요???

 

 

답변 2

·

답변을 작성해보세요.

0

안녕하세요^^

인프런 AI의 답변능력이 대단하네요.

nx, ny 자표가 board 범위 밖으로 나가는 경우의 자표를 continue 해주어야 합니다. 아래 코드가 추가되어야 합니다.

if(nx < 0 || nx >= n || ny < 0 || ny >= m) continue;
import java.io.*;
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 int solution(int[][] board) {
	        int answer = 0;
	        
	        int n=board.length;
	        int m=board[0].length;
	        
	        int[][] dist =new int[n][m];
	        int INF = (int)1e9;
	        PriorityQueue<Node> q = new PriorityQueue<>();
	        q.add(new Node(0,0,0));
	        for(int i=0; i<n; i++) Arrays.fill(dist[i], INF);
	        dist[0][0]=0;
	        
	        int[] dx = {0,0,1,-1};
	        int[] dy = {1,-1,0,0};
	        
	        while(!q.isEmpty()) {
	        	Node tmp = q.poll();
	        	int nowx = tmp.x;
	        	int nowy = tmp.y;
	        	int nowc = tmp.c;
	        	int dir = board[nowx][nowy]-1;
	        	if(nowc>dist[nowx][nowy]) continue;
	        	
	        	for(int i=0; i<4;i++) {
	        		int nx = nowx+dx[i];
	        		int ny = nowy+dy[i];
				if(nx < 0 || nx >= n || ny < 0 || ny >= m) continue;
	        		if(i==dir && dist[nx][ny]>nowc) {
	        			dist[nx][ny] = nowc;
	        			if(q.add(new Node(nx,ny,dist[nx][ny])));
	        		}
	        		else if(i!=dir && dist[nx][ny]>nowc+1) {
	        			dist[nx][ny] = nowc+1;
	        			q.add(new Node(nx,ny,dist[nx][ny]));
	        		}
	        	}
				
	        }
	        answer = dist[n-1][m-1];
	        return answer;
	    }

		public static void main(String[] args){
			Main T = new Main();
			System.out.println(T.solution(new int[][]{{3, 1, 3}, {1, 4, 2}, {4, 2, 3}}));
			System.out.println(T.solution(new int[][]{{3, 2, 1, 3}, {1, 1, 4, 2}, {3, 4, 2, 1}, {1, 2, 2, 4}}));
			System.out.println(T.solution(new int[][]{{3, 2, 1, 3, 1, 2}, {2, 1, 1, 1, 4, 2}, {2, 2, 2, 1, 2, 2}, {1, 3, 3, 4, 4, 4}, {1, 2, 2, 3, 3, 4}}));
			System.out.println(T.solution(new int[][]{{3, 2, 1, 3, 1, 2, 2, 2}, {2, 1, 1, 1, 4, 2, 1, 1}, {2, 2, 2, 1, 2, 2, 3, 4}, {1, 3, 3, 4, 4, 4, 3, 1}, {1, 2, 2, 3, 3, 4, 3, 4}, {1, 2, 2, 3, 3, 1, 1, 1}}));
			System.out.println(T.solution(new int[][]{{1, 2, 3, 2, 1, 3, 1, 2, 2, 2}, {1, 2, 2, 1, 1, 1, 4, 2, 1, 1}, {3, 2, 2, 2, 2, 1, 2, 2, 3, 4}, {3, 3, 1, 3, 3, 4, 4, 4, 3, 1}, {1, 1, 1, 2, 2, 3, 3, 4, 3, 4}, {1, 1, 1, 2, 2, 3, 3, 1, 1, 1}}));
		}
	 }

0

인프런 AI 인턴님의 프로필

인프런 AI 인턴

2023.11.29

안녕하세요, 인프런 AI 인턴입니다.

vkfksaosldk님, 제시해주신 코드에서 발생한 배열 길이가 맞지 않는 문제는 배열의 인덱스가 범위를 벗어난 경우에 발생할 수 있습니다.

코드의 while 루프 내부에서 nxny는 배열 board의 범위를 벗어날 수 있는데, 이를 확인하지 않고 dist[nx][ny]에 접근하려 할 때 ArrayIndexOutOfBoundsException이 발생합니다. 따라서 배열에 접근하기 전 nxny가 배열 범위 안에 있는지 확인하는 조건을 추가해야 합니다.

예를 들어, 다음과 같은 조건을 for 루프 내부에 추가할 수 있습니다:

if(nx >= 0 && ny >= 0 && nx < n && ny < m) {
    // 배열 범위 안에 있을 때만 로직 실행
}

수정된 코드의 일부는 다음과 같습니다:

// ... 기존 코드 ...

while(!q.isEmpty()) {
    Node tmp = q.poll();
    int nowx = tmp.x;
    int nowy = tmp.y;
    int nowc=tmp.c;
    if(nowc>dist[nowx][nowy]) continue;

    for(int i=0; i<4;i++) {
        int nx = nowx+dx[i];
        int ny = nowy+dy[i];

        // 배열 범위를 체크하는 조건을 추가합니다.
        if(nx >= 0 && ny >= 0 && nx < n && ny < m) {
            int dir = board[nowx][nowy]-1;
            if(i==dir && dist[nx][ny]>nowc) {
                dist[nx][ny] = nowc;
                q.add(new Node(nx,ny,dist[nx][ny]));
            }
            else if(i!=dir && dist[nx][ny]>nowc+1) {
                dist[nx][ny] = nowc+1;
                q.add(new Node(nx,ny,dist[nx][ny]));
            }
        }
    }
}

dir 변수의 할당은 if(nx >= 0 && ny >= 0 && nx < n && ny < m) 조건문 안에서 수행되야 하며, i==dir 조건을 체크하기 전에도 범위 검사를 해야 합니다.

해당 부분을 수정하시어 프로그램이 올바르게 작동하는지 확인해 보시기 바랍니다.