공부/Algorithm

[BFS] 완전탐색하여 최단 비용 구하기 - 자외선 차단하기

Egomi 2018. 5. 7. 22:21

* Queue 스택으로 직접 구현 시 주의할 사항

1. rear와 front

rear 나 front를 할 경우, 배열 범위를 초과해 다시 돌아올 수 있으므로

rear = (rear+1) % 스택 수;

front = (front+1) % 스택 수;

하여 스택 초과 시 다시 처음으로 돌아올 수 있도록 한다.

2. isEmpty

rear == front 인 경우 빈 경우이다. 단, 배열이 가득 찬 상태일 수도 있으므로 비어있는지 확인한다.



* 풀어보기
Check[][] 라는 배열에 가장 큰 값으로 초기화를 하고, 첫 시작 점을 Check[0][0]에 넣어준다.가나다 (36pt)

이후부터는 BFS를 활용하여 인접한 곳에 Check[][]값이 Check[x][y] + maps[x][y] < check[x][y]인 경우 최단 거리 이므로

큐에 넣어주고 check[newX][newY]에 Check[x][y] + maps[x][y]를 넣는다.





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import java.util.Scanner;
 
class Info{
    int x;
    int y;
    public Info(int x, int y) {
        super();
        this.x = x;
        this.y = y;
    }
    
}
public class Main {
    static int[][] matrix, check;
    static int N, M, answer, rear, front;
    static int[][] Queue;
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        N = sc.nextInt();
        //M = sc.nextInt();
        matrix = new int[N][N];
        check = new int[N][N];
        Queue = new int[11000][2];
        rear = 0;
        front = 0;
        sc.nextLine();
 
        for(int i=0;i<N;i++){
            String line = sc.nextLine();
            for(int j=0;j<N;j++){
                matrix[i][j] = Integer.parseInt(line.substring(j,j+1));    
                check[i][j]=1000000;
            }
        }
        
        int[] dirX={-1,1,0,0};
        int[] dirY={0,0,1,-1};
        enqueue(00);
        check[0][0= matrix[0][0];
        
        while(!isEmpty()){
            Info info = dequeue();
            int x = info.x;
            int y = info.y;
            for(int k=0;k<4;k++){
                int nexX = x+dirX[k];
                int nexY = y+dirY[k];                
                 if(nexX<0 || nexX>=|| nexY<0 || nexY>=N) continue;
                 if(check[x][y]+matrix[nexX][nexY]<check[nexX][nexY]){
                     check[nexX][nexY] = check[x][y]+matrix[nexX][nexY];
                     enqueue(nexX, nexY);
                 }
            }
        }
        
        System.out.println(check[N-1][N-1]);
    }
 
    private static boolean isEmpty() {
        return front==rear;
    }
 
    private static void enqueue(int x, int y) {
        rear = (rear+1) % 11000;
        Queue[rear][0]=x;
        Queue[rear][1]=y;
    }
 
    private static Info dequeue() {
        front = (front+1)%11000;
        Info info = new Info(Queue[front][0],Queue[front][1]);
        return info;
    }
}
 
 
cs


'공부 > Algorithm' 카테고리의 다른 글

MergeSort  (0) 2018.07.09
Heap Sort  (1) 2018.07.09
최대공약수 최소공배수 및 소수 구하기(미완성)  (0) 2017.10.26
최종정리  (0) 2017.10.20
[삼성 SW EA] 홈 방범 서비스  (0) 2017.10.20