[자바] SWEA 1868 : 파핑파핑 지뢰찾기 (D4)
풀이
방향성 생각
- 약간 그리디하게 접근해야한다.
- 0을 누르면 주변에 있는 1 이상의 숫자에 대해서도 탐지를 해주니, 0에서 먼저 BFS를 돌리고 이후에 1 이상 숫자들을 처리하기.
전체코드
import java.io.*;
import java.util.*;
class Solution {
static int N;
static int[][] arr;
static boolean[][] V;
static int[][] dires = {{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}};
static Map<Character, Integer> cvt = new HashMap<Character, Integer>() {{
put('*', -1);
put('.', 0);
}};
static boolean inside(int x, int y) {
return 0 <= x && x < N && 0 <= y && y < N;
}
static void bfs(int sx, int sy) {
V[sy][sx] = true;
ArrayDeque<int[]> Q = new ArrayDeque<>();
Q.offer(new int[]{sx, sy});
while (!Q.isEmpty()) {
int[] cur = Q.poll();
int x = cur[0], y = cur[1];
for (int[] dir : dires) {
int nx = x + dir[0], ny = y + dir[1];
if (inside(nx, ny) && !V[ny][nx]) {
V[ny][nx] = true;
if (arr[ny][nx] == 0) {
Q.offer(new int[]{nx, ny});
}
}
}
}
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
int TC = Integer.parseInt(br.readLine().trim());
for (int tc = 1; tc <= TC; tc++) {
N = Integer.parseInt(br.readLine().trim());
arr = new int[N][N];
for (int i = 0; i < N; i++) {
String line = br.readLine().trim();
for (int j = 0; j < N; j++) {
arr[i][j] = cvt.get(line.charAt(j));
}
}
for (int y = 0; y < N; y++) {
for (int x = 0; x < N; x++) {
if (arr[y][x] == -1) {
for (int[] dir : dires) {
int nx = x + dir[0], ny = y + dir[1];
if (inside(nx, ny) && arr[ny][nx] >= 0) {
arr[ny][nx]++;
}
}
}
}
}
V = new boolean[N][N];
int count = 0;
for (int y = 0; y < N; y++) {
for (int x = 0; x < N; x++) {
if (arr[y][x] == 0 && !V[y][x]) {
bfs(x, y);
count++;
}
}
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (arr[i][j] > 0 && !V[i][j]) {
count++;
}
}
}
sb.append("#").append(tc).append(" ").append(count).append("\n");
}
System.out.print(sb.toString());
}
}
코멘트
- .
'Algorithm > Greedy' 카테고리의 다른 글
[파이썬] 백준 12904 : A와 B (골드5) (0) | 2024.12.24 |
---|---|
[파이썬] 백준 1083 : 소트 (골드4) (0) | 2024.11.14 |
[파이썬] 백준 9576 : 책 나눠주기 (골드2) (1) | 2024.05.28 |
[파이썬] 백준 3109 : 빵집 (골드2) (0) | 2024.04.14 |
[파이썬] 백준 18234 : 당근훔쳐먹기 (골드3) (0) | 2024.04.02 |
[파이썬] 프로그래머스 : 인사고과 (레벨3) (0) | 2024.04.02 |
[파이썬] 백준 1736 : 쓰레기 치우기 (골드1) (0) | 2024.02.18 |
댓글