Algorithm

[BOJ] 2931. 가스관

프로그래민 2020. 6. 1. 02:04
반응형

BFS를 이용하여 빈칸을 찾는 문제이다.

M에서 시작하여 다음파이프로 이동하면서 만나는 첫번째 빈칸에서 적합한 파이프를 찾는 문제이다. 그 빈칸의 파이프는 해당 빈칸과 연결된 모든 파이프들을 서로 연결시킬수 있는 모양이므로 체크해줘야할 조건이 상당히 많았다. 조건을 체크하는 과정에서 어이없게 실수하는 부분이 있어서 상당히 오랜시간 푼 문제였다. 

BFS를 사용하는 방법 말고도 모든 빈칸을 확인하면서 파이프와 연결되지 않은 곳이 있다면 그 빈칸에 대해 해당하는 파이프 모양을 찾아주는 방법으로도 문제를 접근할 수 있다.

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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
package boj2;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.StringTokenizer;
 
public class Main_bj_2931_가스관 {
    
    static int[] di= {-1,0,1,0};
    static int[] dj= {0,1,0,-1};
    
    static List<Integer>[] pipe;
    
    static int[][] map;
    static int R,C;
    static boolean[][] visit;
    
    static Queue<Pos> queue;
    
    static class Pos{
        int i,j;
        Pos(int i,int j){
            this.i=i;this.j=j;
        }
    }
    
    public static void main(String[] args) throws Exception {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        R=Integer.parseInt(st.nextToken());
        C=Integer.parseInt(st.nextToken());
        
        map=new int[R][C]; visit=new boolean[R][C];
        Pos start=null;
        for(int i=0;i<R;i++) {
            String str=br.readLine();
            for(int j=0;j<C;j++) {
                char ch =str.charAt(j);
                switch (ch) {
                case '|':map[i][j]=1;break;
                case '-':map[i][j]=2;break;
                case '+':map[i][j]=3;break;
                case '1':map[i][j]=4;break;
                case '2':map[i][j]=5;break;
                case '3':map[i][j]=6;break;
                case '4':map[i][j]=7;break;
                case 'M':map[i][j]=-2; start=new Pos(i, j); visit[i][j]=truebreak;
                case 'Z':map[i][j]=-2; visit[i][j]=true;break;
                }
            }
        }
        
        pipe=new ArrayList[8];
        for(int i=1;i<=7;i++)
            pipe[i]=new ArrayList<>();
        
        pipe[1].add(0);pipe[1].add(2);                                    // | 북남
        pipe[2].add(1);pipe[2].add(3);                                    // - 동서
        pipe[3].add(0);pipe[3].add(1);pipe[3].add(2);pipe[3].add(3);    // + 동서남북
        pipe[4].add(1);pipe[4].add(2);                                    // 1 동남
        pipe[5].add(0);pipe[5].add(1);                                    // 2 북동
        pipe[6].add(0);pipe[6].add(3);                                    // 3 북서
        pipe[7].add(3);pipe[7].add(2);                                    // 4 남서
        
        
        queue=new LinkedList<>();
        //첫파이프 찾기
        for(int dir=0;dir<4;dir++) {
            int nextI=start.i+di[dir];
            int nextJ=start.j+dj[dir];
            
            if(nextI<0 || nextI>=|| nextJ<0 ||nextJ>=C)
                continue;
            
            if(map[nextI][nextJ]>=1 && map[nextI][nextJ]<=7) {    //파이프이면
                if(isConnected(dir, map[nextI][nextJ])==true) {    //연결되어 있다면
                    visit[nextI][nextJ]=true;
                    queue.offer(new Pos(nextI, nextJ));
                    break;
                }
            }
        }
        bfs();
    }
    
    
    static void bfs() {
        while(!queue.isEmpty()) {
            Pos cur =queue.poll();
            int curPipe=map[cur.i][cur.j];
            
//            System.out.println(cur.i+","+cur.j);
            
            for(int dir : pipe[curPipe]) {
                int nextI=cur.i+di[dir];
                int nextJ=cur.j+dj[dir];
                
                if(nextI<0 || nextI>=|| nextJ<0 || nextJ>=C)
                    continue;
                
                int nextPipe=map[nextI][nextJ];
                
                //빈칸이 아닌 경우 0 = 빈칸, -2 = 도시
                if(visit[nextI][nextJ]==false && map[nextI][nextJ]!=0 && map[nextI][nextJ]!=-2) {
                    if(isConnected(dir, nextPipe)==true) {
                        visit[nextI][nextJ]=true;
                        queue.offer(new Pos(nextI, nextJ));
                    }
                }
                
                //빈칸인 경우
                if(visit[nextI][nextJ]==false && map[nextI][nextJ]==0) {
                    for(int p=1;p<=7;p++) {        //1번부터 7번까지 파이프 가능한지 확인
                        if(findPipe(nextI,nextJ,p)==true) {
                            print(nextI, nextJ, p);
                            return;
                        }
                    }
                }
            }
        }
    }
    
    //현재 위치에서 파이프가 다른 방향으로 이어지는지 확인
    static boolean findPipe(int i,int j,int p) {
        int count=0;
        
        for(int dir=0;dir<4;dir++) {
            int nextI=i+di[dir];
            int nextJ=j+dj[dir];
            
            if(nextI<0 || nextI>=|| nextJ<0 || nextJ>=C)
                continue;
            if(map[nextI][nextJ]>=1 && map[nextI][nextJ]<=7 && 
                    isConnected(dir, map[nextI][nextJ])==true)
                count+=1;
        }
        
        int count2=0;
        for(int dir : pipe[p]) {
            int nextI=i+di[dir];
            int nextJ=j+dj[dir];
            
            if(nextI<0 || nextI>=|| nextJ<0 || nextJ>=C)
                return false;
            if(map[nextI][nextJ]==0 || map[nextI][nextJ]==-2)
                return false;
            if(isConnected(dir, map[nextI][nextJ])==false)
                return false;
            count2+=1;
            
        }
        
        if(count==count2)
            return true;
        return false;
    }
    
    
    //다음에 갈 파이프가 현재ㅐ 방향의 반대 방향을 가지는지 확인
    static boolean isConnected(int dir, int nextPipe) {        
        int oppDir=oppDir(dir);
        if(pipe[nextPipe].contains(oppDir)==true)
            return true;
        return false;
    }
    
    //반대방향 리턴
    static int oppDir(int dir) {
        if(dir==0)    return 2;
        if(dir==1)    return 3;
        if(dir==2)    return 0;
        if(dir==3)    return 1;
        return -1;
    }
    
    static void print(int i,int j,int pipe) {
        System.out.print((i+1)+ " "+ (j+1+ " ");
        switch (pipe) {
        case 1System.out.println("|"); break;
        case 2System.out.println("-"); break;
        case 3System.out.println("+"); break;
        case 4System.out.println("1"); break;
        case 5System.out.println("2"); break;
        case 6System.out.println("3"); break;
        case 7System.out.println("4"); break;
        }
    }
}
 
           
반응형

'Algorithm' 카테고리의 다른 글

[BOJ] 14391. 종이 조각  (0) 2020.06.03
[BOJ] 15661. 링크와 스타트  (0) 2020.06.02
[BOJ] 17471. 게리맨더링  (0) 2020.05.30
[BOJ] 17069. 파이프 옮기기 2  (0) 2020.05.30
[SWEA] 5215. 햄버거 다이어트  (0) 2020.05.29