๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ”Ž Algorithm/๐Ÿ’ป ๋ฌธ์ œ ํ’€์ด

[๋ฐฑ์ค€] 1018. ์ฒด์ŠคํŒ ๋‹ค์‹œ ์น ํ•˜๊ธฐ

by Seongpyo Hong 2021. 2. 2.

๋ฌธ์ œ

ํ’€์ด

์ฒ˜์Œ์—๋Š” ์ž…๋ ฅ์˜ ํฌ๊ธฐ๋ฅผ ์ฃผ์˜๊นŠ๊ฒŒ ๋ณด์ง€ ์•Š์•„์„œ ์™„์ „ํƒ์ƒ‰์˜ ๋ฐฉ์‹์„ ์ƒ๊ฐํ•˜์ง€ ๋ชปํ–ˆ๋‹ค. ๋‹ค๋ฅธ ๋ฐฉ๋ฒ•์„ ์•„๋ฌด๋ฆฌ ์ƒ๊ฐํ•ด๋ด๋„ ๋– ์˜ค๋ฅด์ง€ ์•Š์•„์„œ ์ฒœ์ฒœํžˆ ๋‹ค์‹œ ์ƒ๊ฐํ•ด๋ดค๋Š”๋ฐ N๊ณผ M์˜ ๋ฒ”์œ„๊ฐ€ 50์ด๊ณ  ๊ฐ€๋Šฅํ•œ ๋ชจ๋“  8x8 ์ •์‚ฌ๊ฐํ˜•์„ ๊ฒ€์‚ฌํ•˜๋”๋ผ๋„ ์ถฉ๋ถ„ํžˆ ์ปค๋ฒ„ ๊ฐ€๋Šฅํ•˜๋‹ค๊ณ  ์ƒ๊ฐํ•ด์„œ ์™„์ „ํƒ์ƒ‰์œผ๋กœ ํ’€์—ˆ๋‹ค.

์™„์ „ํƒ์ƒ‰์„ ํ•  ๋•Œ, ์ฒ˜์Œ ์‹œ์ž‘์ด W์ธ ๊ฒฝ์šฐ์™€ B์ธ ๊ฒฝ์šฐ ๋ชจ๋‘ ์ˆ˜ํ–‰ํ•˜๋„๋ก ํ–ˆ๋‹ค. ์กฐ๊ธˆ ํ—ค๋งธ๋˜ ๋ถ€๋ถ„์€ prev๋ฅผ ์œ ์ง€ํ•˜๋ฉด์„œ prev์™€ ํ˜„์žฌ ๊ฐ’์ด ๊ฐ™์œผ๋ฉด ์นด์šดํŠธ๋ฅผ ํ•ด์ฃผ๋Š” ๋ฐฉ์‹์œผ๋กœ ๊ตฌํ˜„ํ–ˆ๋Š”๋ฐ ์ค„์ด ๋ฐ”๋€” ๋•Œ๋งˆ๋‹ค prev์˜ ๊ฐ’์ด ํ•œ ๋ฒˆ ๋” ๋ณ€๊ฒฝ๋˜์–ด์•ผ ํ•˜๋Š” ๋ถ€๋ถ„์ด์—ˆ๋‹ค. ๊ทธ๋ž˜์„œ ์ฒ˜์Œ ํ–‰์„ ์ œ์™ธํ•œ ๋ชจ๋“  ํ–‰์˜ ์ฒซ ์—ด์€ prev๋ฅผ ํ•œ ๋ฒˆ ๋” ๋ณ€๊ฒฝํ•ด์ฃผ๋Š” ๋ฐฉ์‹์œผ๋กœ ๊ตฌํ˜„ํ•˜์˜€๋‹ค. ๊ตฌํ˜„ ์ฝ”๋“œ๋Š” ์•„๋ž˜์™€ ๊ฐ™๋‹ค.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;

public class Main {
	private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	private static char[][] input;

	public static void main(String[] args) throws IOException {
		StringTokenizer st = new StringTokenizer(br.readLine()); // "2 3"์„ ํ•œ์ค„๋กœ ์ž…๋ ฅ๋ฐ›๊ธฐ
		int N = Integer.parseInt(st.nextToken());
		int M = Integer.parseInt(st.nextToken());
		input = new char[N][M];

		for (int i = 0; i < N; i++) {
			String line = br.readLine();
			for (int j = 0; j < M; j++) {
				input[i][j] = line.charAt(j);
			}
		}

		int min = Integer.MAX_VALUE;
		for (int x = 0; x <= N - 8; x++) {
			for (int y = 0; y <= M - 8; y++) {
				min = Integer.min(min, getCount(x, y, 'W'));
				min = Integer.min(min, getCount(x, y, 'B'));
			}
		}
		System.out.println(min);
	}

	private static int getCount(int x, int y, char start) {
		char prev = start;
		int cnt = (input[x][y] == start) ? 0 : 1;

		for (int i = x; i < x + 8; i++) {
			for (int j = y; j < y + 8; j++) {
				
				if (i == x && j == y) continue;
				if (j == y) {
					prev = ( prev == 'W') ? 'B' : 'W';
				}
				
				if (prev == input[i][j]) {
					cnt++;
				}
				prev = ( prev == 'W') ? 'B' : 'W';
			}
		}
		return cnt;
	}
}

๋Œ“๊ธ€