728x90
๋ฐ์ํ
๐ ๋ฌธ์
์ง๋ ์ ๋ณด๊ฐ N*N ๊ฒฉ์ํ์ ์ฃผ์ด์ง๋ค. ๊ฐ ๊ฒฉ์์๋ ๊ทธ ์ง์ญ์ ๋์ด๊ฐ ์ฐ์ฌ์๋ค. ๊ฐ ๊ฒฉ์ํ์ ์ซ์ ์ค ์์ ์ ์ํ์ข์ฐ ์ซ์๋ณด๋ค ํฐ ์ซ์๋ ๋ด์ฐ๋ฆฌ ์ง์ญ์ด๋ค. ๋ด์ฐ๋ฆฌ ์ง์ญ์ด ๋ช ๊ฐ ์๋์ง ์์๋ด๋ ๋ฌธ์ ์ด๋ค.
๊ฒฉ์์ ๊ฐ์ฅ์๋ฆฌ๋ 0์ผ๋ก ์ด๊ธฐํ ๋์๋ค๊ณ ๊ฐ์ ํ๋ค.
๋ง์ฝ N = 5์ด๊ณ , ๊ฒฉ์ํ์ ์ซ์๊ฐ ๋ค์๊ณผ ๊ฐ๋ค๋ฉด ๋ด์ฐ๋ฆฌ์ ๊ฐ์๋ 10๊ฐ์ด๋ค.
0 | 0 | 0 | 0 | 0 | 0 | 0 |
0 | 5 | 3 | 7 | 2 | 3 | 0 |
0 | 3 | 7 | 1 | 6 | 1 | 0 |
0 | 7 | 2 | 5 | 3 | 4 | 0 |
0 | 4 | 3 | 6 | 4 | 1 | 0 |
0 | 8 | 7 | 3 | 5 | 2 | 0 |
0 | 0 | 0 | 0 | 0 | 0 | 0 |
์ํ์ข์ฐ๋ฅผ ํ๋ณํ ๋๋ dx = [-1, 0 ,1, 0], dy = [0, 1, 0, -1]๊ณผ ๊ฐ์ด ๋ฐฉํฅ ๋ฒกํฐ๋ฅผ ๋ฏธ๋ฆฌ ์ค์ ํด์ฃผ๋ฉด ์ข๋ค.
๐จ๐ป๐ป ๋์ ํ์ด ๋ฐฉ๋ฒ
- num์ 0์ผ๋ก ์ด๊ธฐํํ ํ ๊ฒฉ์ ๊ฐ์ฅ์๋ฆฌ์ ์ ๊ทผํ ๊ฒฝ์ฐ, ์ํ์ข์ฐ ์ซ์๋ณด๋ค ํฐ ๊ฒฝ์ฐ์ num + 1์ ํด์ค๋ค.
- ์ํ์ข์ฐ์ ๋น๊ต๋ฅผ ๋๋ธ ํ num์ด 4์ ๊ฐ๋ค๋ฉด ๋ด์ฐ๋ฆฌ ์ง์ญ์ด๋ฏ๋ก answer + 1์ ํด์ค๋ค.
๐จ๐ป๐ซ ๊ฐ์ฌ๋ ํ์ด ๋ฐฉ๋ฒ
- flag๋ฅผ 1๋ก ์ด๊ธฐํํ ํ ์ํ์ข์ฐ ์ซ์๊ฐ ์์ ๋ณด๋ค ํฌ๊ฑฐ๋ ๊ฐ์ ๊ฒฝ์ฐ์ flag๋ฅผ 0์ผ๋ก ์ฌํ ๋นํ๋ค.
- ์ํ์ข์ฐ์ ๋น๊ต๋ฅผ ๋๋ธ ํ์๋ flag๊ฐ 1์ด๋ผ๋ฉด ๋ด์ฐ๋ฆฌ ์ง์ญ์ด๋ฏ๋ก answer + 1์ ํด์ค๋ค.
๐ ํ์ด
// ๋์ ํ์ด ๋ฐฉ๋ฒ
function solution(arr) {
let answer = 0;
const n = arr.length;
const dx = [-1, 0, 1, 0];
const dy = [0, 1, 0, -1];
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
let num = 0;
for (let k = 0; k < 4; k++) {
const nx = i + dx[k];
const ny = j + dy[k];
if (nx >= 0 && ny >= 0 && nx < n && ny < n) {
if (arr[i][j] > arr[nx][ny]) num++;
} else num++;
}
if (num === 4) 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));
// ๊ฐ์ฌ๋ ํ์ด ๋ฐฉ๋ฒ
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 && ny >= 0 && nx < n && ny < n) {
if (arr[i][j] <= arr[nx][ny]) {
flag = 0;
break;
}
}
}
if (flag === 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));
'Algorithm > ์ธํ๋ฐ(inflearn)' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[JavaScript/section 3] 02 - ์ ํจํ ํฐ๋ฆฐ๋๋กฌ (0) | 2022.09.08 |
---|---|
[JavaScript/section 3] 01 - ํ๋ฌธ ๋ฌธ์์ด (0) | 2022.09.08 |
[JavaScript/section 2] 06 - ๊ฒฉ์ํ ์ต๋ํฉ (0) | 2022.09.07 |
[JavaScript/section 2] 05 - ๋ฑ์ ๊ตฌํ๊ธฐ (0) | 2022.09.07 |
[JavaScript/section 2] 04 - ์ ์ ๊ณ์ฐ (0) | 2022.09.06 |