• 문제 링크
6189번: Munching
Bessie loves her grass and loves to hurry to the barn for her evening milking session. She has partitioned the pasture into a rectilinear grid of R (1 <= R <= 100) rows and C (1 <= C <= 100) columns and marked the squares as grass or rocky (she can't eat r
www.acmicpc.net
• 풀이 코드
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken()), m = Integer.parseInt(st.nextToken());
Queue<Pair> q = new ArrayDeque<>();
int[][] mat = new int[n][m], dir = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int y = 0, x = 0;
for (int i = 0; i < n; i++) {
String s = br.readLine();
for (int j = 0; j < m; j++) {
char c = s.charAt(j);
switch (c) {
case '*':
mat[i][j] = -1;
break;
case 'B':
q.offer(new Pair(i, j));
break;
case 'C':
y = i;
x = j;
break;
}
}
}
while (!q.isEmpty()) {
Pair cur = q.poll();
if (cur.y == y && cur.x == x) break;
for (int[] d : dir) {
int ny = cur.y + d[0], nx = cur.x + d[1];
if (ny < 0 || ny >= n || nx < 0 || nx >= m || mat[ny][nx] != 0) continue;
q.offer(new Pair(ny, nx));
mat[ny][nx] = mat[cur.y][cur.x] + 1;
}
}
bw.write(String.valueOf(mat[y][x]));
bw.flush();
}
private static class Pair {
int y, x;
Pair(int y, int x) {
this.y = y;
this.x = x;
}
}
}
'Problem Solving > Baekjoon' 카테고리의 다른 글
[백준] 6207 Cow Picnic - Graph Theory / Java (0) | 2023.12.15 |
---|---|
[백준] 18788 Swapity Swap - Graph Theory / Java (0) | 2023.12.14 |
[백준] 6080 Bad Grass - Graph Theory / Java (0) | 2023.12.12 |
[백준] 10104 Party Invitation - Data Structure / Java (0) | 2023.12.11 |
[백준] 25325 학생 인기도 측정 - Data Structure / Java (0) | 2023.12.10 |
댓글