• 문제 링크
4993번: Red and Black
There is a rectangular room, covered with square tiles. Each tile is colored either red or black. A man is standing on a black tile. From a tile, he can move to one of four adjacent tiles. But he can't move on red tiles, he can move only on black tiles. Wr
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 {
static int w, h;
static boolean[][] mat;
static Queue<Pair> q = new ArrayDeque<>();
static int[][] dir = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringBuilder sb = new StringBuilder();
String s;
while (!(s = br.readLine()).equals("0 0")) {
StringTokenizer st = new StringTokenizer(s);
w = Integer.parseInt(st.nextToken());
h = Integer.parseInt(st.nextToken());
mat = new boolean[h][w];
int y = 0, x = 0;
for (int i = 0; i < h; i++) {
s = br.readLine();
for (int j = 0; j < w; j++) {
char c = s.charAt(j);
mat[i][j] = c == '#';
if (c == '@') {
y = i;
x = j;
}
}
}
sb.append(bfs(new Pair(y, x))).append("\n");
q.clear();
}
bw.write(sb.toString());
bw.flush();
}
private static int bfs(Pair src) {
q.offer(src);
mat[src.y][src.x] = true;
int cnt = 1;
while (!q.isEmpty()) {
Pair cur = q.poll();
for (int[] d : dir) {
int ny = cur.y + d[0], nx = cur.x + d[1];
if (ny < 0 || ny >= h || nx < 0 || nx >= w || mat[ny][nx]) continue;
q.offer(new Pair(ny, nx));
mat[ny][nx] = true;
cnt++;
}
}
return cnt;
}
private static class Pair {
int y, x;
Pair(int y, int x) {
this.y = y;
this.x = x;
}
}
}
'Problem Solving > Baekjoon' 카테고리의 다른 글
[백준] 15761 Lemonade Line - Greedy / Java (0) | 2023.12.19 |
---|---|
[백준] 28323 불안정한 수열 - Greedy / Java (0) | 2023.12.18 |
[백준] 15242 Knight - Graph Theory / Java (0) | 2023.12.16 |
[백준] 6207 Cow Picnic - Graph Theory / Java (0) | 2023.12.15 |
[백준] 18788 Swapity Swap - Graph Theory / Java (0) | 2023.12.14 |
댓글