728x90
๐ 22 - ๊ฒฉ์ํ ์ต๋ํฉ
n*n
์ ๊ฒฉ์ํ์์ ๊ฐ ํ, ๊ฐ ์ด, ๋ ๋๊ฐ์ ์ ํฉ ์ค ๊ฐ์ฅ ํฐ ๊ฐ์ ์ถ๋ ฅํ๋ฉด ๋๋๋ฐ, ์ฒซ ๋ฒ์งธ๋ก row
์ ํฉ์ ๊ตฌํ ๋๋ ๋ฐ๋ณต๋ฌธ์ ํ๋๋ง ์ ์ธํด์ reduce
๋ฅผ ์ด์ฉํ๊ณ , column
์ ํฉ์ ์ค์ฒฉ๋ฐ๋ณต๋ฌธ์ ์ ์ธํด์ i, j
๊ฐ์ ๊ตฌํ๋ค. ๋๊ฐ์ ์ ์ข์ธก ์๋จ์์ ์ฐ์ธก ํ๋จ์ ๋ฐฉํฅ์ ๋๊ฐ์ arr[i][i]๊ณผ
์ฐ์ธก ์๋จ์์ ์ข์ธก ํ๋จ์ ๋ฐฉํฅ์ ๋๊ฐ์ arr[i][n-i-1]์
๋ฐฉ๋ฒ์ ์ด์ฉํด์ ๊ตฌํ๋ค.
// ๊ฐ๋ก, ์ธ๋ก, ๋๊ฐ์ ๋ก์ง์ ๊ฐ๊ฐ ์์ฑํ ์ฝ๋
let n = 5;
let arr = [
[10, 13, 10, 12, 15],
[12, 39, 30, 23, 11],
[11, 25, 50, 53, 15],
[19, 27, 29, 37, 27],
[19, 13, 30, 13, 19],
];
console.log(solution(n, arr));
function solution(n, arr) {
let row = (column = normal = reverse = 0);
// row
for (let i = 0; i < n; i++) {
let rowSum = arr[i].reduce((acc, cur) => acc + cur, 0);
row = Math.max(row, rowSum);
}
// column
for (let i = 0; i < n; i++) {
let columnSum = 0;
for (let j = 0; j < n; j++) {
columnSum += arr[j][i];
}
column = Math.max(column, columnSum);
}
// diagonal
for (let i = 0; i < n; i++) {
normal += arr[i][i];
reverse += arr[i][n-i-1];
}
return Math.max(row, column, normal, reverse);
}
// ๊ฐ๋ก + ์ธ๋ก, ๋๊ฐ์ ๋ก์ง์ ์์ฑํ ์ฝ๋
let n = 5;
let arr = [
[10, 13, 10, 12, 15],
[12, 39, 30, 23, 11],
[11, 25, 50, 53, 15],
[19, 27, 29, 37, 27],
[19, 13, 30, 13, 19],
];
console.log(solution(n, arr));
function solution(n, arr) {
let answer = 0;
let normal = reverse = 0;
// row, column
for (let i = 0; i < n; i++) {
let row = column = 0;
for (let j = 0; j < n; j++) {
row += arr[i][j];
column += arr[j][i];
}
answer = Math.max(row, column);
}
// diagonal
for (let i = 0; i < n; i++) {
normal += arr[i][i];
reverse += arr[i][n-i-1];
}
answer = Math.max(answer, normal, reverse);
return answer;
}
๋ฐ์ํ
'Algorithm > ์ธํ๋ฐ(inflearn)' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[ ์๋ฐ์คํฌ๋ฆฝํธ(JavaScript) ] 24 - ํ๋ฌธ ๋ฌธ์์ด (0) | 2021.08.17 |
---|---|
[ ์๋ฐ์คํฌ๋ฆฝํธ(JavaScript) ] 23 - ๋ด์ฐ๋ฆฌ (0) | 2021.08.17 |
[ ์๋ฐ์คํฌ๋ฆฝํธ(JavaScript) ] 21 - ๋ฑ์ ๊ตฌํ๊ธฐ (0) | 2021.08.13 |
[ ์๋ฐ์คํฌ๋ฆฝํธ(JavaScript) ] 20 - ์ ์ ๊ณ์ฐ (0) | 2021.08.13 |
[ ์๋ฐ์คํฌ๋ฆฝํธ(JavaScript) ] 19 - ๊ฐ์ ๋ฐ์ ๋ณด (0) | 2021.08.13 |
๋๊ธ