3085번: 사탕 게임

예제 3의 경우 4번 행의 Y와 C를 바꾸면 사탕 네 개를 먹을 수 있다.

www.acmicpc.net

 

풀이 방법

배열 전체를 돌면서 기준이 되는 사탕과 인접한 사탕의 색깔이 다른 경우 위치를 교환해, 행과 열을 확인하여 최대 먹을 수 있는 사탕을 계산해 주었습니다.

 

 

코드

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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
 
public class Main_BJ_3085_사탕게임 {
    
    static int [] dx = {-1,0,1,0};
    static int [] dy = {0,1,0,-1};
    
    static int N, max=0;
    static char [][] map;
    
    public static void main(String[] args) throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        N = Integer.parseInt(br.readLine());
        
        map = new char[N][N];
        
        for(int i=0;i<N;i++) {
            String line = br.readLine();
            for(int j=0;j<N;j++) {
                map[i][j] = line.charAt(j);
            }
        }
        
        candy();
        System.out.println(max);
    }
    
    public static void candy() {
        for(int x=0;x<N;x++) {
            for(int y=0;y<N;y++) {
                
                for(int d=0;d<4;d++) { // 상 하 좌 우 인접한곳
                    int nx = x + dx[d];
                    int ny = y + dy[d];
                    
                    if(range(nx,ny) && map[x][y]!=map[nx][ny]) {
                        char temp = map[x][y];
                        map[x][y] = map[nx][ny];
                        map[nx][ny] = temp;
                        
                        check(); //먹을 수 있는 사탕 개수 확인
                        
                        temp = map[x][y];
                        map[x][y] = map[nx][ny];
                        map[nx][ny] = temp;
                    }
                }
            }
        }
    }
    
    public static boolean range(int x, int y) {
        return x>=0 && x<&& y>=0 && y<N;
    }
    
    public static void check() {
        
        for(int i=0;i<N;i++) {
            for(int j=0;j<N;j++) {
                count(i,j);
            }
        }    
    }
    
    public static void count(int x, int y) {
        
        int yy=y, xx=x, row=1, col=1;
        //연속된 행
        for(int i=y+1;i<N;i++) {
            if(map[x][yy]==map[x][i]) {
                row++;
                yy = i; 
            }else break;
        }
        
        //연속된 
        for(int i=x+1;i<N;i++) {
            if(map[xx][y]==map[i][y]) {
                col++;
                xx = i;
            }else break;
        }
        
        int result = Math.max(row, col);
        max = Math.max(result, max);
    }
 
}
cs
 
 
 

 

 

11724번: 연결 요소의 개수

첫째 줄에 정점의 개수 N과 간선의 개수 M이 주어진다. (1 ≤ N ≤ 1,000, 0 ≤ M ≤ N×(N-1)/2) 둘째 줄부터 M개의 줄에 간선의 양 끝점 u와 v가 주어진다. (1 ≤ u, v ≤ N, u ≠ v) 같은 간선은 한 번만 주

www.acmicpc.net

 

풀이 과정

방향 없는 그래프가 주어졌을 때, 연결 요소의 개수를 구하는 문제였습니다.

 

저는 Union Find 알고리즘을 이용하여 문제를 풀었으며,

각각의 간선의 부모(Find)가 다른 경우 Union 메서드를 통해 간선을 연결시켜 주었습니다.

 

M번의 반복문이 끝난 뒤, HashSet을 이용해 연결요소의 개수를 구해주었습니다.

 

[같은 문제의 배열 풀이방법]

 

백준 11724번 연결 요소의 개수 [JAVA]

문제 방향 없는 그래프가 주어졌을 때, 연결 요소 (Connected Component)의 개수를 구하는 프로그램을 작성하시오. 입력 첫째 줄에 정점의 개수 N과 간선의 개수 M이 주어진다. (1 ≤ N ≤ 1,000, 0 ≤ M ≤ N

javaju.tistory.com

 

코드

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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.StringTokenizer;
 
public class Main_BJ_11724_연결요소의개수 {
    
    static int N,M;
    static int [] parents;
 
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        HashSet<Integer> hs = new HashSet<>();
        
        StringTokenizer st;
        
        st = new StringTokenizer(br.readLine());
        
        N = Integer.parseInt(st.nextToken());
        M = Integer.parseInt(st.nextToken());
        
        parents = new int[N+1];
        
        for(int i=1;i<parents.length;i++) parents[i] = i;
        
        for(int i=0;i<M;i++) {
            st = new StringTokenizer(br.readLine());
            
            int u = Integer.parseInt(st.nextToken());
            int v = Integer.parseInt(st.nextToken());
            
            if(find(u)!=find(v)) union(u,v);
                
        }
        
        for(int i=1;i<parents.length;i++) {
            hs.add(find(parents[i]));
        }
        
        System.out.println(hs.size());
    }
    
    public static void union(int a,int b) {
        int aRoot = find(a);
        int bRoot = find(b);
        
        if(aRoot>bRoot) parents[aRoot] = bRoot;
        else parents[bRoot] = aRoot;
    }
    
    public static int find(int a) {
        if(parents[a]==a) return a;
        return parents[a] = find(parents[a]);
    }
 
}
cs

 

'문제 > 백준' 카테고리의 다른 글

백준 13549번 숨바꼭질3 [JAVA]  (0) 2021.11.23
백준 3085번 사탕 게임 [JAVA]  (0) 2021.11.18
백준 1753 최단경로 [JAVA]  (0) 2021.11.06
백준 15686 치킨 배달 [JAVA]  (0) 2021.10.23
백준 1406번 에디터 [JAVA]  (0) 2021.10.20

1. WebSocket connection to failed

개발 서버에서는 WebSocket을 통한 채팅이 정상적으로 됐는데, 배포한 서버에서는 Connection 오류가 발생하면서 채팅 기능이 제대로 동작하지 않았다..

 

 

서버 환경

  • Ubuntu 20.04
  • Nginx 1.18.0

 

💡 해결방법

1. /nginx.conf > proxy_http_version, proxy_set_header 부분 추가

location /endpoint {
		proxy_pass <http://localhost>:포트번호/endpoint;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";

		proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
}

에러 해결 ❌

 

 

2. 위의 방법이 안될경우

location /endpoint {
		proxy_pass <http://localhost>:포트번호/endpoint;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
		proxy_set_header Origin ""; // 이 부분 추가

		proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
}

proxy_set_header Origin ""; 을 추가해보자!

contextLoads() FALIED error

  • build 중contextLoads() FALIED 에러가 발생했다.

💡 해결방법 💡

  • main에는 application.properties 파일이 존재하지만 test에는 application.properties 파일이 없어서 발생하는 문제!
  • Spring Boot 에서 ApplicationTest.java 파일에 @SpringBootTest 주석처리 해주면 해결!
 

1753번: 최단경로

첫째 줄에 정점의 개수 V와 간선의 개수 E가 주어진다. (1 ≤ V ≤ 20,000, 1 ≤ E ≤ 300,000) 모든 정점에는 1부터 V까지 번호가 매겨져 있다고 가정한다. 둘째 줄에는 시작 정점의 번호 K(1 ≤ K ≤ V)가

www.acmicpc.net

 

풀이 방법

i번 정점으로의 최단 경로를 구하는 문제였습니다.

 

해당 간선의 정보를 list[]에 넣어주었습니다. 우선순위 큐를 이용해 가중치가 작은 간선부터 탐색을 시작했습니다.

시작점에서 연결된 간선 중 아직 방문하지 않았으며 해당 정점으로 바로가는 것보다 다른 곳을 거쳐 도착하는 거리가 더 짧으면 distance 배열에 거리를 변경해주고 간선 정보를 큐에에 넣어 이와 같은 과정을 반복해주었습니다.

 

 

[아래 링크는 다른 방법으로 푼 1753번 최단경로]

 

백준 1753번 최단경로 [JAVA]

문제 방향그래프가 주어지면 주어진 시작점에서 다른 모든 정점으로의 최단 경로를 구하는 프로그램을 작성하시오. 단, 모든 간선의 가중치는 10 이하의 자연수이다. 입력 첫째 줄에 정점의 개

javaju.tistory.com

[다른 방법으로 푼 1753번 최단경로]

 

 

코드

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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
 
public class Main_BJ_1753_최단경로_PQ {
    
    static class info implements Comparable<info>{
        int end, weight;
 
        public info(int end, int weight) {
            super();
            this.end = end;
            this.weight = weight;
        }
 
        @Override
        public int compareTo(info o) {
            return this.weight-o.weight;
        }
        
    }
    
    static int V,E;
    static int [] distance;
    static ArrayList<info> node[];
    static boolean [] visited;
 
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        StringTokenizer st;
        
        
        st = new StringTokenizer(br.readLine());
        
        V = Integer.parseInt(st.nextToken());
        E = Integer.parseInt(st.nextToken());
        
        distance = new int[V+1];
        node = new ArrayList[V+1];
        visited = new boolean[V+1];
        
        for(int i=1;i<distance.length;i++) node[i] = new ArrayList<>();
        
        int start = Integer.parseInt(br.readLine());
        
        for(int i=1;i<distance.length;i++) distance[i] = Integer.MAX_VALUE;
        distance[start] = 0;
        
        for(int i=0;i<E;i++) {
            st = new StringTokenizer(br.readLine());
            
            int go = Integer.parseInt(st.nextToken());
            int end = Integer.parseInt(st.nextToken());
            int value = Integer.parseInt(st.nextToken());
            
            node[go].add(new info(end,value));
        }
        
        dijkstra(start);
        
        for(int i=1;i<distance.length;i++) {
            if(distance[i]==Integer.MAX_VALUE) sb.append("INF\n");
            else sb.append(distance[i]+"\n");
        }
        System.out.println(sb.toString());
 
    }
    
    public static void dijkstra(int start) {
        PriorityQueue<info> pq = new PriorityQueue<>();
        pq.add(new info(start,0));
        
        while(!pq.isEmpty()) {
            info temp = pq.poll();
            
            if(!visited[temp.end]) {
                for(info item : node[temp.end]) {
                    if(distance[item.end]> distance[temp.end]+item.weight) {
                        distance[item.end]=distance[temp.end]+item.weight;
                        pq.add(new info(item.end,distance[item.end]));
                    }
                }
                visited[temp.end] = true;
            }
        }
        
    }
 
}
cs

 

npm not found error

  • build 중 npm install 에서 npm not found 에러가 발생했다.

 

💡 해결방법 💡

1️⃣ NodeJS 플러그인 설치

  • Jenkins 관리 -> 플러그인 관리 -> 설치 가능 탭 -> NodeJs 검색 후 설치

 

 

2️⃣ NodeJs 플러그인 설정

  • Jenkins 관리 -> Global Tool Configuration
  • NodeJS -> Add NodeJS에서 위에와 같이 설정 후 저장

 

3️⃣ Job 설정

  • 구성 -> 빌드 환경 설정

 

15686번: 치킨 배달

크기가 N×N인 도시가 있다. 도시는 1×1크기의 칸으로 나누어져 있다. 도시의 각 칸은 빈 칸, 치킨집, 집 중 하나이다. 도시의 칸은 (r, c)와 같은 형태로 나타내고, r행 c열 또는 위에서부터 r번째 칸

www.acmicpc.net

 

풀이 방법

치킨집을 최대 M개 골랐을 때, 도시의 치킨 거리의 최솟값을 구하는 문제였습니다.

 

도시의 정보가 주어질 때,

1인 경우에는 home 리스트에 2인 경우에는 chicken 리스트에 위치 정보를 넣어주었습니다.

 

최대 M개의 치킨 집을 선택하기 위해서 조합을 이용했고,

M개를 선택했을 때 check() 메서드에서 집의 위치로부터 치킨집들의 최소 거리를 구해주었습니다.

 

 

코드

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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
 
public class Main_BJ_15686_치킨배달 {
    
    static class info{
        int x, y;
 
        public info(int x, int y) {
            super();
            this.x = x;
            this.y = y;
        }
    }
    
    static int N,M, min=Integer.MAX_VALUE;
    static int [][] map;
    
    static ArrayList<info> chicken = new ArrayList<>();
    static ArrayList<info> choice = new ArrayList<>();
    static ArrayList<info> home = new ArrayList<>();
 
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st;
        
        st = new StringTokenizer(br.readLine());
        
        N = Integer.parseInt(st.nextToken());
        M = Integer.parseInt(st.nextToken());
        
        map = new int[N][N];
        
        for(int i=0;i<N;i++) {
            st = new StringTokenizer(br.readLine());
            for(int j=0;j<N;j++) {
                map[i][j] = Integer.parseInt(st.nextToken());
                if(map[i][j]==2) chicken.add(new info(i,j));
                else if(map[i][j]==1) home.add(new info(i,j));
            }
        }
        
        comb(0,0);
        System.out.println(min);
    }
    
    public static void comb(int cnt, int start) {
        if(cnt==M) {
            check();
            return;
        }
        
        for(int i=start;i<chicken.size();i++) {
            choice.add(new info(chicken.get(i).x, chicken.get(i).y));
            comb(cnt+1, i+1);
            choice.remove(choice.size()-1);
        }
    }
    
    public static void check() {
        int distance, sum=0;
        for(int i=0;i<home.size();i++) {
            distance=Integer.MAX_VALUE;
            for(int j=0;j<choice.size();j++) {
                distance = Math.min(distance, Math.abs(home.get(i).x-choice.get(j).x)+Math.abs(home.get(i).y-choice.get(j).y));
            }
            sum+=distance;
        }
        
        min = Math.min(min, sum);
    }
 
}
cs

 

 

1406번: 에디터

첫째 줄에는 초기에 편집기에 입력되어 있는 문자열이 주어진다. 이 문자열은 길이가 N이고, 영어 소문자로만 이루어져 있으며, 길이는 100,000을 넘지 않는다. 둘째 줄에는 입력할 명령어의 개수

www.acmicpc.net

 

풀이 방법

해당 명령어를 수행하고 난 후 편집기에 입력되어 있는 문자열을 출력하는 문제였습니다.

 

저는 초기 편집기에 입력되어 있는 문자열을 list에 넣고 list의 사이즈를 index로 해당 커서의 위치를 변경해주면서 명령어를 수행해주었습니다. 하지만 채점 결과 시간 초과가 발생했고 이 문제를 해결하기 위해 질문게시판과 블로그를 찾아봤습니다.

 

이 문제는 삽입/삭제가 빈번하게 일어나는데 빠른 처리시간을 요구하고 있었습니다. 그래서 더 빠르게 현재 위치를 찾으면서 삽입/삭제를 처리할 수 있는 방법을 찾았습니다.

 

바로 ListIterator을 사용하는 것이었습니다.

 

ListIterator는 컬렉션 요소에 접근할 때 한 방향으로만 이동하는 것이 아니라 양방으로 이동할 수 있습니다. 그래서 커서를 앞 뒤로 움직일 수 있도록 해당 메서드를 이용하여 커서를 움직이며 문제를 해결해나갔습니다.

 

ListIterator를 이용해 문제를 풀었지만 채점 결과 또 시간 초과가 났고,

마지막에 편집기에 입력되어있는 문자열을 출력해주기 위해 사용된 기존 for문을 향상된 for문을 이용하여 출력하니 정답을 맞출 수 있었습니다. 

 

코드

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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.ListIterator;
 
public class Main_BJ_1406_에디터 {
 
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
 
        LinkedList<Character> list = new LinkedList<>();
        
        String command = br.readLine();
        
        for(int i=0;i<command.length();i++) {
            list.add(command.charAt(i));
        }
        
        ListIterator<Character> liter = list.listIterator();
        while (liter.hasNext()) {
            liter.next(); 
        }
 
        int M = Integer.parseInt(br.readLine());
        
        for(int i=0;i<M;i++) {
            String str = br.readLine();
            char com = str.charAt(0);
            if(com=='L') {
                if(liter.hasPrevious()) liter.previous();
            }
            else if(com=='D') {
                if(liter.hasNext()) liter.next();
            }
            else if(com=='B') {
                if(liter.hasPrevious()) { 
                    liter.previous(); 
                    liter.remove(); 
                }
            }
            else if(com=='P') {
                liter.add(str.charAt(2));
            }
        }
        
        for (char c : list) { 
            sb.append(c);
        } 
        
        System.out.println(sb.toString());
    }
 
}
cs

 

 

'문제 > 백준' 카테고리의 다른 글

백준 1753 최단경로 [JAVA]  (0) 2021.11.06
백준 15686 치킨 배달 [JAVA]  (0) 2021.10.23
백준 8972번 미친 아두이노 [JAVA]  (0) 2021.10.19
백준 23056번 참가자 명단 [JAVA]  (0) 2021.10.17
백준 8911번 거북이 [JAVA]  (0) 2021.10.13

Iterator<E> 인터페이스

  • 컬렉션에 저장된 요소를 읽어오는 방법을 iterator인터페이스로 표준화
    LinkedList<Integer> list = new LinkedList<Integer>(); 
    
    list.add(4); 
    list.add(3); 
    list.add(2); 
    list.add(1); 
    
    Iterator<Integer> iter = list.iterator(); 
    
    while(iter.hasNext()){ //hasNext : 다음 요소를 가지고 있으면 true / 아니면 false 반환 
    	System.out.print(iter.next()+" "); //next : 다음 요소 반환 
    } 
    
    // 4 3 2 1​

 

ListIterator<E> 인터페이스

  • Iterator 인터페이스를 상속받아 여러 기능을 추가한 인터페이스
  • Iterator 인터페이스는 컬렉션 요소에 접근할 때 한 방향으로만 이동할 수 있지만 ListIterator 인터페이스는 양방향으로 이동할 수 있다.
LinkedList<Integer> list = new LinkedList<Integer>(); 

list.add(4); 
list.add(2); 
list.add(3); 
list.add(1); 

ListIterator<Integer> iter = list.listIterator(); 

while (iter.hasNext()) { //hasNext : 순방향으로 순회할 때 다음 요소가 있으면 true 아니면 false 
	System.out.print(iter.next() + " "); //next : 다음 요소를 반환하고 커서 위치 순방향으로 이동 
} 

while (iter.hasPrevious()) { //hasPrevious : 역방향으로 순회할 때 다음 요소가 있으면 true 아니면 false 
	System.out.print(iter.previous() + " "); //previous : 이전 요소를 반환하고 커서 위치 역방향으로 이동 
} 

// 4 2 3 1 
// 1 3 2 4
 

8972번: 미친 아두이노

요즘 종수는 아두이노를 이용해 "Robots"이라는 게임을 만들었다. 종수는 아두이노 한대를 조정하며, 미친 아두이노를 피해다녀야 한다. 미친 아두이노는 종수의 아두이노를 향해 점점 다가온다.

www.acmicpc.net

 

풀이 방법

입력으로 주어진 방향대로 종수가 움직였을 때, 보드의 상태를 구하는 프로그램을 구하는 문제였습니다.

 

  1. 먼저, 종수가 아두이노를 8가지 방향(수직, 수평, 대각선)으로 이동시키거나, 그 위치에 그대로 놔둔다.
  2. 종수의 아두이노 위치 =  미친 아두이노 위치 게임 오버
  3. 종수의 위치를 (r1,s1), 미친 아두이노의 위치를 (r2, s2)라고 했을 때, |r1-r2| + |s1-s2|가 가장 작아지는 방향으로 이동
  4. 종수의 아두이노 위치 =  미친 아두이노 위치 게임 오버
  5. 2개 또는 그 이상의 미친 아두이노가 같은 칸에 있는 경우에는 큰 폭발이 일어나고, 그 칸에 있는 아두이노는 모두 파괴된다.

 저는 종수의 위치를 넣을 리스트와 미친 아두이노의 위치 정보를 넣을 리스트를 이용해 종수 아두이노 먼저 움직이고 난 뒤, 종수의 아두이노 위치와 미친 아두이노의 위치가 같은 지 확인해 주었습니다.

그 후 종수의 위치를 기반으로 미친 아두이노와 거리가 가장 짧아 지는 방향으로 이동해 시켜 준 뒤, 마찬가지로 종수의 아두이노 위치와 미친 아두이노의 위치가 같은 지 확인해 주었습니다. 미친 아두이노를 다 움직이고 난 뒤, 겹친 아두이노는 폭발시켜 없애주고 입력으로 주어진만큼 이 과정을 반복해주었습니다.

 

코드

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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
 
public class Main_BJ_8972_미친아두이노 {
    
    static class info{
        int x, y;
 
        public info(int x, int y) {
            super();
            this.x = x;
            this.y = y;
        }
        
    }
    
    static int R,C;
    static char [][] map;
    
    static Queue<info> jongsoo = new LinkedList<>();
    static Queue<info> crazy = new LinkedList<>();
    
    static int [] dx = {0,1,1,1,0,0,0,-1,-1,-1};
    static int [] dy = {0,-1,0,1,-1,0,1,-1,0,1};
 
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st;
        
        st = new StringTokenizer(br.readLine());
        
        R = Integer.parseInt(st.nextToken());
        C = Integer.parseInt(st.nextToken());
        
        map = new char[R][C];
        
        for(int i=0;i<R;i++) {
            String command = br.readLine();
            for(int j=0;j<C;j++) {
                map[i][j] = command.charAt(j);
                if(map[i][j]=='I') jongsoo.add(new info(i,j));
                else if(map[i][j]=='R') crazy.add(new info(i,j));
            }
        }
        
        int count=1;
        
        boolean flag = true;
        String direction = br.readLine();
        for(int i=0;i<direction.length();i++) {
            if(!jongsoo_move(direction.charAt(i)-48)) {
                flag = false;
                break;
            }
            if(!crazy_move()) {
                flag = false;
                break;
            }
            map();
            count++;
        }
        if(!flag) System.out.println("kraj "+ count);
        else print();
    }
    
    
    public static boolean jongsoo_move(int dir) {
        info temp = jongsoo.poll();
        
        int nx = temp.x + dx[dir];
        int ny = temp.y + dy[dir];
 
        if(map[nx][ny]=='R'return false;
        else {
            jongsoo.add(new info(nx,ny));
            if(dir!=5) {
                map[nx][ny] = map[temp.x][temp.y];
                map[temp.x][temp.y] = '.';
            }
            return true;
        }
    }
    
    public static boolean crazy_move() {
        int[][] temp = new int[R][C];
        
        info js = jongsoo.peek();
        
        int jsX = js.x;
        int jsY = js.y;
        
        while(!crazy.isEmpty()) {
            
            info cr = crazy.poll(); 
            
            int len = Integer.MAX_VALUE;
            int dir = 0;
            for(int j=1;j<10;j++) {
                if(j==5continue;
                int nx = cr.x+dx[j];
                int ny = cr.y+dy[j];
                
                if(nx < 0 || nx >= R || ny < 0 || ny >= C) continue;
                
                int distance = Math.abs(jsX-nx) + Math.abs(jsY-ny);
                
                if(distance<len) {
                    len = distance;
                    dir = j;
                }
            }
            
            int moveX = cr.x+dx[dir];
            int moveY = cr.y+dy[dir];
            
            
            if(map[moveX][moveY]=='I') {
                return false;
            }
            
            temp[moveX][moveY] += 1;
        }
        for(int i = 0; i < R; i++) {
            for(int j = 0; j < C; j++) {
                if(temp[i][j] == 1) {
                    crazy.add(new info(i, j));
                }
            }
        }
        
        return true;
    }
    
    public static void map() {
        for(int i=0;i<R;i++) Arrays.fill(map[i], '.');
        
        info js = jongsoo.peek();
        
        map[js.x][js.y] = 'I';
        
        for(int i=0;i<crazy.size();i++) {
            info cr = crazy.poll();
            map[cr.x][cr.y] = 'R';
            crazy.add(new info(cr.x, cr.y));
        }
    }
    
    public static void print() {
        for(int i=0;i<R;i++) {
            for(int j=0;j<C;j++) {
                System.out.print(map[i][j]);
            }
            System.out.println();
        }
    }
 
}
 
cs

 

'문제 > 백준' 카테고리의 다른 글

백준 15686 치킨 배달 [JAVA]  (0) 2021.10.23
백준 1406번 에디터 [JAVA]  (0) 2021.10.20
백준 23056번 참가자 명단 [JAVA]  (0) 2021.10.17
백준 8911번 거북이 [JAVA]  (0) 2021.10.13
백준 6137번 문자열 생성 [JAVA]  (0) 2021.09.26

+ Recent posts