지도 정보가 N*N 격자판에 주어진다.
각 격자 판의 숫자 중 자신의 상하좌우 숫자보다 큰 숫자는 봉우리 지역.
봉우리 지역이 몇 개 있는 지 알아내는 프로그램을 작성하세요.
격자의 가장자리는 0으로 초기화 되었다고 가정한다.

ex) 위 격자판의 봉우리 개수는 10개
<script>
function solution(arr){
let answer =0,temp=[], n= arr.length;
for(let i=0; i<n+2;i++){
temp.push([]);
for(let j=0; j<n+2;j++){
if(i===0 || i===n+1) {temp[i].push(0);}
else if(j===0 || j ===n+1) {temp[i].push(0);}
else{
temp[i].push(arr[i-1][j-1]);
}
}
}
for(let i=1;i<temp.length-1;i++){
for(let j=1;j<temp.length-1;j++){
if(temp[i][j]>temp[i-1][j]&&
temp[i][j]>temp[i][j-1] &&
temp[i][j]>temp[i+1][j] &&
temp[i][j]>temp[i][j+1]){
answer ++;
}
}
}
return answer;
}
let arr=[[5, 3, 7, 2, 3],
[3, 7, 1, 6, 1],
[7, 2, 5, 3, 4],
[4, 3, 6, 4, 1],
[8, 7, 3, 5, 2]];
console.log(solution(arr));
</script>
위쪽 이중for문을 통해, 격자판의 가장자리에 0을 추가로 삽입해준다.
아래쪽 이중for문을 통해, 각 요소가 봉우리인지를 확인한다.
<script>
function solution(arr){
let answer = 0;
let n = arr.length;
let dx = [-1,0,1,0];
let dy = [0,1,0,-1];
for(let i=0; i<n;i++){
for(let j=0;j<n;j++){
let flag =1;
for(let k=0;k<4;k++){
let nx = i+dx[k];
let ny = j+dy[k];
if(nx>=0 && nx<n && ny>=0 && ny<n &&arr[nx][ny]>=arr[i][j]){
flag = 0;
break;
}
}
if(flag) answer ++;
}
}
return answer;
}
let arr=[[5, 3, 7, 2, 3],
[3, 7, 1, 6, 1],
[7, 2, 5, 3, 4],
[4, 3, 6, 4, 1],
[8, 7, 3, 5, 2]];
console.log(solution(arr));
</script>
dx, dy 를 통해 4방(동서남북)을 표현한다.
마지막 for문 (k)를 통해 사방의 값이 현재 인덱스의 값보다 크다면 flag값을 0을 주며, 마지막 반복문을 빠져나온다.
마지막 반복문을 온전히 성공하면(봉우리라면) answer값 증가.