편집 기록

편집 기록
  • 프로필 알 수 없는 사용자님의 편집
    날짜2016.04.12

    자바로 알고리즘 문제를 풀고 있는데 ArrayIndexOutOfBoundsException 에러가 납니다.


    백준 온라인 저지에서 문제 풀고있는데 답이 안나옵니다... C로 코딩했을때는 에러가 안나는데 자바로만 하면 if(arr[x][y-1] == 1 && y-1 >= 0) 줄에서 java.lang.ArrayIndexOutOfBoundsException 에러가 납니다... 왜 나는지 이유는 알겠는데 어떻게 해결해야 할지 모르겠네요...

    고수님들 답변 부탁드립니다.

    이미지 이름이나 설명을 여기에 넣어주세요.

    이미지 이름이나 설명을 여기에 넣어주세요.

    package baekjun;
    
    import java.util.Scanner;
    
    public class problem6{
        static int M,N,K;
        static int[][] arr;
        static int[][] visited;
        static int testcase;
    
    
        public static void main(String[] args){
            int myX = 0;
            int myY = 0;
    
            Scanner sc = new Scanner(System.in);
    
            testcase = sc.nextInt();
            M = sc.nextInt();
            N = sc.nextInt();
            K = sc.nextInt();
    
            arr = new int[M][N];
    
            for (int i = 0; i < M; i++) {
                for (int j = 0; j < N; j++) {
                    arr[i][j] = 0;
                }
            }
    
            for(int k = 0; k<testcase; k++) {
                int count = 0;
    
                for (int i = 0; i < K; i++){
                    myX = sc.nextInt();
                    myY = sc.nextInt();
                    arr[myX][myY] = 1;
                }
    
                for(int i = 0; i<M; i++) {
                    for (int j = 0; j<N; j++) {
                        if(arr[i][j] == 1) {
                            DFS(i, j);
                            count++;
                        }
                    }
                }
                System.out.println(count);
            }
        }
    
        static void DFS(int x, int y){
            arr[x][y] = 0;
    
            if(arr[x+1][y] == 1 && x+1 < M) 
                DFS(x+1, y);
            if(arr[x][y+1] == 1 && y+1 < N) 
                DFS(x, y+1);
            if(arr[x-1][y] == 1 && x-1 >= 0) 
                DFS(x-1, y);
            if(arr[x][y-1] == 1 && y-1 >= 0) 
                DFS(x, y-1);
        }
    }
    }