코딩테스트

[JAVA] 원형 Queue를 사용한 너비우선탐색(BFS) Queue제네릭 사용 X (미로탈출)

dackyy 2022. 7. 15. 16:17
반응형

미로는 정해진 값으로 사용했으며 원형 queue를 구현하여 queue 크기를 5로 설정하고 구현했습니다.

package Day3;

import java.util.ArrayList;
import java.util.Arrays;

public class MiroQueue {
    static int[][] map = {{0,0,0,-1,0,0,0,-1}, {0,-1,0,-1,0,-1,0,-1}, {0,-1,0,-1,-1,-1,0,-1}, {0,0,0,0,0,0,0,-1}, {-1,-1,-1,0,-1,-1,-1,-1}, {0,0,-1,0,-1,0,0,-1}, {-1,0,0,0,-1,0,-1,-1}, {-1,-1,-1,0,0,0,0,0}};
    static String[] queue = new String [4];
    static ArrayList<String> log = new ArrayList<String>();
    static int front, rear, num;
    static String start = "0,0";
    static String exit = "7,7";
    static String temp = "";
    public static void main(String[] args) throws OverflowIntQueueException {
        front = 0;
        rear = 0;
        num = 0;
        disp();
        enQueue(start);
        while(!exit.equals(temp)){
            search(deQueue());
            System.out.print("queue :" + Arrays.toString(queue)+"\n");
            System.out.print("현재위치 : "+temp+" ");
        }
    }
    static void search(String str) throws OverflowIntQueueException {
        String [] temp = str.split(",");
        int x = Integer.parseInt(temp[0]);
        int y = Integer.parseInt(temp[1]);
        for(int i = x-1;i<=x+1;i+=2){
            valid(i,y);
        }
        for(int j = y-1;j<=y+1;j+=2){
            valid(x,j);
        }
    }
    static void valid(int x, int y) throws OverflowIntQueueException {
        String tmp = x + "," + y;
        if(x <0 || y <0) { }
        else if(x > 7 || y > 7) { }
        else if (map[x][y] == -1){ }
        else if (Arrays.asList(queue).contains(tmp)){ }
        else{
            if(!log.contains(tmp)) {
                temp = tmp;
                enQueue(tmp);
            }
        }

    }
    static void disp(){
        for (int[] ints : map) {
            for (int anInt : ints) {
                if (anInt == -1)
                    System.out.print(" ■");
                else {
                    System.out.print(" □");
                }
            }
            System.out.println();
        }
    }
    static void enQueue(String n) throws OverflowIntQueueException{
        if (num >= queue.length)
            throw new OverflowIntQueueException();
        queue[rear++] = n;
        num++;
        if (rear == queue.length-1)
            rear = 0;
    }
    static String deQueue() throws OverflowIntQueueException{
        if (num <= 0)
            throw new OverflowIntQueueException();
        String n = queue[front];
        queue[front++] = null;
        num--;
        if(front == queue.length-1)
            front = 0;
        log.add(n);
        return n;
    }
}
package Day3;

public class OverflowIntQueueException extends Exception {
    public OverflowIntQueueException() {}
}
반응형