[BaekJoon] 9328번 - 열쇠 [Java][C++]
[BaekJoon] 9328번 - 열쇠 [Java][C++]
1. 문제 풀이
1층 빌딩의 정보가 주어져 있을 때 훔쳐올 수 있는 문서의 최대 개수를 구하는 문제다. BFS를 활용하면 해결할 수 있는데 먼저 빌딩 외부에서 빌딩의 경계 중 통과할 수 있는 곳을 통해 진입한다는 점에서 빌딩 외부에 빈 공간으로 이루어진 패딩을 한 칸 주고 $(0, 0)$ 에서 탐색을 시작해서 시작점을 찾는 로직을 간소화했다.
BFS의 경우 노드들을 담는 큐와 별도로 현재 열쇠가 없어서 열 수 없는 문을 담는 자료구조를 두었다. BFS 탐색 중 열쇠를 발견하면 해당 열쇠로 열 수 있는 문들을 큐로 옮겨서 탐색을 진행해주면 된다.
탐색은 방문하지 않았으면서 벽이 아니면 문이거나 열쇠가 있거나 문서가 있거나 빈 공간이거나 4가지 경우 중 하나인데 문일 경우 현재 열 수 없으면 별도의 자료구조에, 열 수 있으면 방문하고, 열쇠의 경우 방문하며 열쇠 정보를 갱신하고 해당 열쇠로 열 수 있는 문들을 큐로 옮겨주었다. 빈 공간이나 문서면 일단 방문하고 방문한 노드를 큐에서 꺼낼 때 문서면 개수를 세줬다.
현재 열쇠가 없어서 열 수 없는 문은 열쇠의 종류가 26가지이므로 큐 배열을 활용해서 효율적으로 처리해줬다.
2. 코드
1. 풀이 [Java]
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
import java.io.*;
import java.util.*;
public class Main {
static final int[] dr = {-1, 0, 1, 0};
static final int[] dc = {0, 1, 0, -1};
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
StringTokenizer st;
int T = Integer.parseInt(br.readLine());
for (int tc = 1; tc <= T; tc++) {
st = new StringTokenizer(br.readLine());
int h = Integer.parseInt(st.nextToken());
int w = Integer.parseInt(st.nextToken());
int N = 1 + h + 1;
int M = 1 + w + 1;
char[][] map = new char[N][M];
for (int i = 0; i < N; i++) {
map[i][0] = map[i][M - 1] = '.';
}
for (int j = 0; j < M; j++) {
map[0][j] = map[N - 1][j] = '.';
}
for (int i = 1; i <= h; i++) {
String input = br.readLine();
for (int j = 1; j <= w; j++) {
map[i][j] = input.charAt(j - 1);
}
}
boolean[] hasKey = new boolean[26];
String str = br.readLine();
if (!str.equals("0")) {
for (char c : str.toCharArray()) {
hasKey[c - 'a'] = true;
}
}
int cnt = bfs(N, M, map, hasKey);
sb.append(cnt).append("\n");
}
System.out.println(sb);
}
static boolean isKey(char c) {
return 'a' <= c && c <= 'z';
}
static boolean isDoor(char c) {
return 'A' <= c && c <= 'Z';
}
static int bfs(int N, int M, char[][] map, boolean[] hasKey) {
Queue<int[]> q = new ArrayDeque<>();
q.offer(new int[]{0, 0});
Queue<int[]>[] doors = new ArrayDeque[26];
for (int i = 0; i < 26; i++) {
doors[i] = new ArrayDeque<>();
}
boolean[][] visited = new boolean[N][M];
visited[0][0] = true;
int cnt = 0;
while (!q.isEmpty()) {
int[] node = q.poll();
if (map[node[0]][node[1]] == '$') cnt++;
for (int d = 0; d < 4; d++) {
int nr = node[0] + dr[d];
int nc = node[1] + dc[d];
if (nr < 0 || nr >= N || nc < 0 || nc >= M) continue;
if (map[nr][nc] == '*' || visited[nr][nc]) continue;
if (isDoor(map[nr][nc])) {
if (!hasKey[map[nr][nc] - 'A']) {
doors[map[nr][nc] - 'A'].offer(new int[]{nr, nc});
continue;
}
}
if (isKey(map[nr][nc])) {
hasKey[map[nr][nc] - 'a'] = true;
q.addAll(doors[map[nr][nc] - 'a']);
}
q.offer(new int[]{nr, nc});
visited[nr][nc] = true;
}
}
return cnt;
}
}
2. 풀이 [C++]
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
#include <bits/stdc++.h>
using namespace std;
int dr[4] = {-1, 0, 1, 0};
int dc[4] = {0, 1, 0, -1};
char grid[1 + 100 + 1][1 + 100 + 1];
bool visited[1 + 100 + 1][1 + 100 + 1];
int bfs(int n, int m, vector<bool>& hasKey) {
queue<pair<int, int>> q;
q.push({0, 0});
vector<queue<pair<int, int>>> doors(26);
visited[0][0] = true;
int cnt = 0;
while (!q.empty()) {
auto [r, c] = q.front();
q.pop();
if (grid[r][c] == '$') cnt++;
for (int d = 0; d < 4; d++) {
int nr = r + dr[d];
int nc = c + dc[d];
if (nr < 0 || nr >= n || nc < 0 || nc >= m) continue;
if (grid[nr][nc] == '*' || visited[nr][nc]) continue;
if ('A' <= grid[nr][nc] && grid[nr][nc] <= 'Z') {
if (!hasKey[grid[nr][nc] - 'A']) {
doors[grid[nr][nc] - 'A'].push({nr, nc});
continue;
}
}
if ('a' <= grid[nr][nc] && grid[nr][nc] <= 'z') {
hasKey[grid[nr][nc] - 'a'] = true;
while (!doors[grid[nr][nc] - 'a'].empty()) {
q.push(doors[grid[nr][nc] - 'a'].front());
doors[grid[nr][nc] - 'a'].pop();
}
}
q.push({nr, nc});
visited[nr][nc] = true;
}
}
return cnt;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
for (int tc = 1; tc <= t; tc++) {
int h, w;
cin >> h >> w;
int n = h + 2;
int m = w + 2;
memset(grid, 0, sizeof(grid));
memset(visited, 0, sizeof(visited));
for (int i = 0; i < n; i++) {
grid[i][0] = grid[i][m - 1] = '.';
}
for (int j = 0; j < m; j++) {
grid[0][j] = grid[n - 1][j] = '.';
}
for (int i = 1; i <= h; i++) {
string s;
cin >> s;
for (int j = 1; j <= w; j++) {
grid[i][j] = s[j - 1];
}
}
vector<bool> hasKey(26);
string s;
cin >> s;
if (!(s == "0")) {
for (char c : s) {
hasKey[c - 'a'] = true;
}
}
int cnt = bfs(n, m, hasKey);
cout << cnt << '\n';
}
}
This post is licensed under CC BY 4.0 by the author.