강의

멘토링

로드맵

Inflearn brand logo image

인프런 커뮤니티 질문&답변

youngyou1324님의 프로필 이미지
youngyou1324

작성한 질문수

자바 코딩테스트 - it 대기업 유제

2. "집으로 이동" 코드 해설

집으로 이동 문제 코드

작성

·

94

0

안녕하세요 강사님

강사님께서 제시해준 답변 코드에서 의문이 있어서 질문드립니다.

여기서

조건절

 

if(nx <= 10001 && ch[0][nx] == 0){

~

를 보면 nx<=10001이 nx<10001이 되어야 되지 않나요?

ch가 int[][] ch = new int[2][10001]; 이건데

index out of bound 에러 날 것 같습니다.

 

import java.util.*;
class Solution {
	public int solution(int[] pool, int a, int b, int home){
		int[][] ch = new int[2][10001];
		for(int x : pool){
			ch[0][x] = 1;
			ch[1][x] = 1;
		}
		Queue<int[]> Q = new LinkedList<>();
		ch[0][0] = 1;
		ch[1][0] = 1;
		Q.offer(new int[]{0, 0});
		int L = 0;
		while(!Q.isEmpty()){
			int len = Q.size();
			for(int i = 0; i < len; i++){
				int[] cur = Q.poll();
				if(cur[0] == home) return L;
				int nx = cur[0] + a;
				if(nx <= 10001 && ch[0][nx] == 0){
					ch[0][nx] = 1;
					Q.offer(new int[]{nx, 0});
				}
				nx = cur[0] - b;
				if(nx >= 0 && ch[1][nx] == 0 && cur[1] == 0){
					ch[1][nx] = 1;
					Q.offer(new int[]{nx, 1});
				}
			}
			L++;
		}
		return -1;
	}

	public static void main(String[] args){
		Solution T = new Solution();
		System.out.println(T.solution(new int[]{11, 7, 20}, 3, 2, 10));	
		System.out.println(T.solution(new int[]{1, 15, 11}, 3, 2, 5));	
		System.out.println(T.solution(new int[]{9, 15, 35, 30, 20}, 2, 1, 25));	
		System.out.println(T.solution(new int[]{5, 12, 7, 19, 23}, 3, 5, 18));	
		System.out.println(T.solution(new int[]{10, 15, 20}, 3, 2, 2));	
	}
}

답변 1

0

김태원님의 프로필 이미지
김태원
지식공유자

안녕하세요^^

그렇네요. 왜 같다는 했을 까요 ㅜㅜ

찾아주셔서 감사합니다.

youngyou1324님의 프로필 이미지
youngyou1324

작성한 질문수

질문하기