백준 1018 : 체스판 다시 칠하기

HARIBO·2022년 1월 27일
0

풀이

  • 왼쪽 위의 행 / 열을 받아, 다시 칠해야 되는 칸의 수를 반환하는 getCount함수를 작성해 사용했다.
  • 위의 함수를 최소한으로 사용하기 위해 8*8의 판을 만들 수 있는 경우만 getCount함수를 사용했다.
var fs = require("fs")


const stdin = fs.readFileSync('/dev/stdin').toString().split('\n');

//첫 번째 인자는 행, 뒤 번째 인자는 열의 수
const rowCol = stdin[0].split(" ");

const map = new Array(Number(rowCol[0]));

for(let i = 0; i < Number(rowCol[0]); i++){
    map[i] = stdin[i + 1].split('');
}



//첫 지점을 받아서  8*8 판을 검사하고, 다시 칠해야 할 칸의 수를 반환한다.
function getCount(row, col){
    //false는 검은색, true는 하얀색
    //첫 지점이 검은색 이어야 되는 경우
    let flag = false;
    let whiteCount = 0;
    for(let i = row; i < row + 8; i++){
        for(let j = col; j < col + 8; j++){
            if(map[i][j] === 'W' && !flag){
                whiteCount++;
            } else if(map[i][j] === 'B' && flag){
                whiteCount++;
            }
            if(j !== col + 7) flag = !flag;
        }
    }

    //첫 지점이 하얀색 이어야 되는 경우
    let blackCount = 0;
    flag = true;
    for(let i = row; i < row + 8; i++){
        for(let j = col; j < col + 8; j++){
            if(map[i][j] === 'W' && !flag){
                blackCount++;
            } else if(map[i][j] === 'B' && flag){
                blackCount++;
            }
            if(j !== col + 7) flag = !flag;
        }
    }
    return Math.min(whiteCount, blackCount);
}


let answer = Number.MAX_SAFE_INTEGER;

//시작점(왼쪽 위)을 기준으로 8*8의 타일이 존재할 경우만 getCount함수를 쓴다.
for(let i = 0; i < rowCol[0]; i++){
    for(let j = 0; j < rowCol[1]; j++){
        if(i + 8 <= rowCol[0] && j + 8 <= rowCol[1]){
            answer = Math.min(answer, getCount(i, j));
        }
    }
    
}

console.log(answer)

개선할 점

  • getCount함수에서 하얀 칸 / 검은 칸이 시작점인 부분에서 같은 코드가 두 번 반복된다.
let flag = false;
    let whiteCount = 0;
    for(let i = row; i < row + 8; i++){
        for(let j = col; j < col + 8; j++){
            if(map[i][j] === 'W' && !flag){
                whiteCount++;
            } else if(map[i][j] === 'B' && flag){
                whiteCount++;
            }
            if(j !== col + 7) flag = !flag;
        }
    }

캡슐화하면 반복을 줄일 수 있지 않을까?

0개의 댓글