https://programmers.co.kr/learn/courses/30/lessons/81302
1) 가로줄, 세로줄을 요소 셋 씩 묶어 거리두기를 위반한 사례가 있는지 체크하는 함수를 만든다.
2) 2x2로 요소를 묶어 대각선으로 거리두기를 위반한 사례가 있는지 체크하는 함수를 만든다.
3) map으로 places의 각 요소를 위 두 함수로 검토한다.
function checkRowAndCol(place) {
let result = true;
for(let i = 0; i < place.length; i++){
for(let j = 0; j < place[i].length - 2; j++){
let manhattan = [place[i][j], place[i][j + 1], place[i][j + 2]];
let pNum = manhattan.filter(el => el === "P").length;
if (pNum >= 2 && manhattan[1] !== "X"){
result = false;
break;
}
}
}
for(let i = 0; i < place.length; i++){
for(let j = 0; j < place[i].length - 2; j++){
let manhattan = [place[j][i], place[j + 1][i], place[j + 2][i]];
let pNum = manhattan.filter(el => el === "P").length;
if (pNum >= 2 && manhattan[1] !== "X"){
result = false;
break;
}
}
}
return result;
}
function checkCross(place){
let result = true;
for(let i = 0; i < place.length - 1; i++){
for(let j = 0; j < place[i].length - 1; j++){
let manhattan = [place[i][j], place[i][j + 1], place[i + 1][j], place[i + 1][j + 1]];
let pNum = manhattan.filter(el => el === "P").length;
let xNum = manhattan.filter(el => el === "X").length;
if (pNum >= 2 && xNum < 2){
result = false;
break;
}
}
}
return result;
}
function solution(places) {
return places.map(place => checkRowAndCol(place) && checkCross(place) ? 1 : 0)
}
function solution(places) {
let answer = [];
for (let i = 0; i < places.length; i++) {
answer.push(keep_dist(places[i]));
}
return answer;
}
// 거리두기를 대각선과 가로줄을 모두 한 번에 체크하고 있다.
function keep_dist(place) {
place = place.map(v => v.split(''));
for (let row = 0; row < 5; row++) {
for (let col = 0; col < 5; col++) {
if (place[row][col] === 'P') {
// 가로 한칸 체크 (왼쪽 방향은 굳이 체크하지 않는다.)
if (col < 4 && place[row][col + 1] === 'P') {
return 0;
}
// 가로 두칸 체크 (가로 두 칸에 요소가 없는 경우를 염두에 두고 조건문에 조건을 걸어주고 있다.)
if (col < 3 && place[row][col + 2] === 'P' && place[row][col + 1] === 'O') {
return 0;
}
// 세로 한칸 체크 (위쪽 방향은 굳이 체크하지 않는다.)
if (row < 4 && place[row + 1][col] === 'P') {
return 0;
}
// 세로 두칸 체크 (세로 두 칸에 요소가 없는 경우를 염두에 두고 조건문에 조건을 걸어주고 있다.)
if (row < 3 && place[row + 2][col] === 'P' && place[row + 1][col] === 'O') {
return 0;
}
// 아래 왼쪽 대각
if (row < 4 && place[row + 1][col - 1] === 'P') {
if (place[row + 1][col] === 'O' || place[row][col - 1] === 'O') {
return 0;
}
}
//아래 오른쪽 대각
if (row < 4 && col < 4 && place[row + 1][col + 1] === 'P') {
if (place[row + 1][col] === 'O' || place[row][col + 1] === 'O') {
return 0;
}
}
}
}
}
return 1;
}