하얀 칸

이윤설·2024년 5월 7일


https://www.acmicpc.net/problem/1100

제출코드

import java.io.*;

public class Main {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        Character[][] array = new Character[8][8];
        Character[][] inputArray = new Character[8][8];

        for (int i = 0; i < 8; i++) {
            String input = br.readLine();
            for (int j = 0; j < input.length(); j++) {
                char c = input.charAt(j);
                inputArray[i][j] = c;
            }
        }

        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                // 행과 열의 인덱스 합이 짝수인 경우 'W', 홀수면 'B'
                if ((i + j) % 2 == 0) {
                    array[i][j] = 'W';
                } else {
                    array[i][j] = 'B';
                }
            }
        }

        int count = 0;
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                if (array[i][j].equals('W')) {
                    if (inputArray[i][j].equals('F')) {
                        count++;
                    }
                }
            }
        }

        System.out.println(count);
    }
}
  • 바둑판을 채우는게 제일 어려웠다..;;
    array[i][j]에서 [i]가 (열이) 0이거나 짝수면 차례대로 흰색부터, 홀수면 검은색부터 넣어야 했다. 근데 생각보다 간단하게 해결할 수 있었다. i와 j를 더해서 짝수면 흰색을, 홀수면 검은색을 할당해줌으로써 해결할 수 있었다. 이러한 로직은 바둑판과 같은 구조에 자주 쓰일 것 같으니 기억하는 것이 좋을 것같다.

  • 두 개의 2차원 배열을 만들어서 같은 인덱스가 각각 'F' 이고, 'W'인 경우 count를 더하는 방식을 사용했다.

그런데 더 간단하게 구현할 수 있는 방법이 있었다.

모범답안

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int count = 0;
        for (int i = 0; i < 8; i++) {
            String s = br.readLine();
            for (int j = 0; j < 8; j++) {
                if (s.charAt(j) == 'F' && (i+j)%2 == 0) count++;
            }
        }
        System.out.print(count);
    }
}

우선 (0,0)은 흰 칸이라고 문제에서 주어졌다. 즉, (1,0)과 (0,1)은 검은색 칸이다. 칸을 (i, j)라고 했을 때 i + j가 짝수이면 흰색 칸인 것이다.

이중 for-loop으로 접근하면 되며, 입력으로 주어지는 문자열의 줄을 i라고 하고 그 줄의 문자열을 j번째 인덱스라고 하겠다.
만약에 (i, j)가 F이고 i + j가 짝수이면 카운트를 1씩 증가해 주는 식으로 접근하면 된다.

출처) https://propercoding.tistory.com/78

profile
화려한 외면이 아닌 단단한 내면

0개의 댓글