๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm/์ธํ”„๋Ÿฐ(inflearn)

[ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ(JavaScript) ] 22 - ๊ฒฉ์žํŒ ์ตœ๋Œ€ํ•ฉ

by YWTechIT 2021. 8. 17.
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;
}
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€