본문 바로가기
알고리즘/SWEA

[Java] SWEA 1868번 파핑파핑 지뢰찾기

by 컴공맨 2021. 3. 5.
 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com


풀이

우선 8면이 전부 숫자인 부분들만 찾아서 dfs를 통해 숫자를 공개하면서 클릭 횟수를 증가시키고 전부 숫자로 둘러쌓인 부분을 다 찾으면 남아있는 '.' 부분을 찾아 클릭 횟수를 증가시키는 방법으로 해결했습니다.


코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Solution {
	public static int N, answer;
	public static char[][] table;
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder("");
		
		int T = Integer.parseInt(br.readLine());
		for (int tc = 1; tc <= T; ++tc) {
			N = Integer.parseInt(br.readLine());
			
			table = new char[N][N];
			
			for (int i = 0; i < N; ++i) {
				table[i] = br.readLine().toCharArray();
			}
			
			answer = 0;
			
			for (int i = 0; i < N; ++i) {
				for (int j = 0; j < N; ++j) {
					if (table[i][j] == '.' && isOpen(i, j)) {
						answer++;
						table[i][j] = 'x';
						go(i, j);
					}
				}
			}
			
			for (int i = 0; i < N; ++i) {
				for (int j = 0; j < N; ++j) {
					if (table[i][j] == '.') {
						answer++;
					}
				}
			}
			
			sb.append("#").append(tc).append(" ").append(answer).append("\n");
		}
		
		System.out.println(sb);
	}
	
	public static int[] dy = {-1, -1, -1, 0, 0, 1, 1, 1};
	public static int[] dx = {-1, 0, 1, -1, 1, -1, 0, 1};
	public static void go(int y, int x) {
		if (isOpen(y, x)) {
			for (int i = 0; i < 8; ++i) {
				int ny = y + dy[i];
				int nx = x + dx[i];
				
				if (ny < 0 || nx < 0 || ny >= N || nx >= N) {
					continue;
				}
				
				if (table[ny][nx] == '.') {
					table[ny][nx] = 'x';
					go(ny, nx);
				}
			}
		}
	}
	
	public static boolean isOpen(int y, int x) {
		for (int i = 0; i < 8; ++i) {
			int ny = y + dy[i];
			int nx = x + dx[i];
			
			if (ny < 0 || nx < 0 || ny >= N || nx >= N) {
				continue;
			}
			
			if (table[ny][nx] == '*') {
				return false;
			}
		}
		
		return true;
	}
}

 

pyo7410/Algorithm

1일 1커밋을 목표로! Contribute to pyo7410/Algorithm development by creating an account on GitHub.

github.com

 

'알고리즘 > SWEA' 카테고리의 다른 글

[Java] SWEA 1238번 Contact  (0) 2021.03.09
[Java] SWEA 1218번 괄호 짝짓기  (0) 2021.03.08
[Java] SWEA 1486번 장훈이의 높은 선반  (0) 2021.03.04
[Java] SWEA 1249번 보급로  (0) 2021.03.03
[Java] SWEA 1211번 Ladder2  (0) 2021.03.02