๐Ÿง  codingtest/javascript 100์ œ

๋ฌธ์ œ 95. ๋„์žฅ์ฐ๊ธฐ

awesomeyelim 2022. 4. 28. 08:31
728x90

 

 

 

 

  • ๋นˆ ์ข…์ด์— stemp ๋ชจ์–‘์œผ๋กœ ์ƒ๊ธด ๋„์žฅ์„ 90º ๋กœ ํšŒ์ „ํ•˜๋ฉฐ ์ฐ๋Š”๋‹ค. ๋„์žฅ์˜ ํฌ๊ธฐ๋Š” N*N ํฌ๊ธฐ, ๋„์žฅ์ด ์ฐํžˆ๋Š” ๋ถ€๋ถ„์€ 1์ด์ƒ์˜ ์ž์—ฐ์ˆ˜์™€ ๋„์žฅ์ด ์ฐํžˆ์ง€ ์•Š๋Š” 0์œผ๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ์Œ.
  • ์ข…์ด์— ์ฐํžŒ ๋„์žฅํšŸ์ˆ˜๋ฅผ ํ‘œํ˜„ํ•œ stmp ๋ฐฐ์—ด๊ณผ ์–ผ๋งŒํผ ํšŒ์ „ํ•  ๊ฒƒ์ธ์ง€ ์•Œ๋ ค์ฃผ๋Š” ํšŒ์ „์ˆ˜ k๋ฅผ ์ž…๋ ฅ๋ฐ›์•˜์„๋•Œ

๊ฐ ์œ„์น˜์—์„œ ๋ช‡๋ฒˆ ๋„์žฅ์ด ์ฐํ˜”๋Š”์ง€ ๊ทธ ๊ฒฐ๊ณผ๊ฐ’์„ ์ถœ๋ ฅํ•˜์‹œ์˜ค

 

 

 

 

 

// ์ž…๋ ฅ
๋„์žฅ = [
  [1, 1, 1, 2],
  [2, 0, 0, 0],
  [1, 1, 1, 1],
  [0, 0, 0, 0],
];

ํšŒ์ „ = 1;

// ์ถœ๋ ฅ
[
  [1, 2, 3, 3],
  [2, 1, 0, 1],
  [1, 2, 1, 2],
  [0, 1, 0, 2],
];

 

 

 

๋ฏธ๋ฆฌ ์ƒ๊ฐํ•ด ๋ด์•ผํ•  ๊ฒƒ

  • ์–ด๋–ค ๊ทœ์น™์œผ๋กœ ๋„๋Š”์ง€ ์ƒ๊ฐํ•ด๋ณธ๋‹ค.

i,j -> j,N-1-i

0,0 -> 0,3
0,1 -> 1,3
0,2 -> 2,3
0,3 -> 3,3

1,0 -> 0,2
1,1 -> 1,2
1,2 -> 2,2
1,3 -> 3,2

2,0 -> 0,1
2,1 -> 1,1
2,2 -> 2,1
2,3 -> 3,1

3,0 -> 0,0
3,1 -> 1,0
3,2 -> 2,0
3,3 -> 3,0

 

 

 

 

๋‹ต

let stmp = [
  [1, 1, 1, 2],
  [2, 0, 0, 0], 
  [1, 1, 1, 1],
  [0, 0, 0, 0],
];

let k = 1;

function sol(stmp, k) {
  let n = stmp.length;
  let p = [];

  for (let i = 0; i < n; i++) {
    p.push(Array(n).fill(0)); //0์œผ๋กœ ์ฑ„์›Œ์ง„ n*n ๋ฐฐ์—ด์„ ๋งŒ๋“ค์–ด์ค€๋‹ค
  }
  //   console.log(p)
  // ํšŒ์ „์‹œํ‚ค๊ธฐ ์ „ ํ•œ๋ฒˆ ์ฐ์–ด์ฃผ๊ธฐ
  p = sum_matrix(p, stmp);

  for (let i = 0; i < k; i++) {
    stmp = rotate(stmp);
    p = sum_matrix(p, stmp);
  }

  return p;
}

// ํšŒ์ „
function rotate(stmp) {
  let n = stmp.length;
  let rot = [];

  for (let i = 0; i < n; i++) {
    rot.push(Array(n).fill(0));
  }

  for (let i = 0; i < n; i++) {
    for (let j = 0; j < n; j++) {
      rot[j][n - 1 - i] = stmp[i][j];
    }
  }
  return rot;
}

//์ดํ•ฉ
function sum_matrix(p, stmp) {
  let n = stmp.length;
  for (let i = 0; i < n; i++) {
    for (let j = 0; j < n; j++) {
      p[i][j] += stmp[i][j];
    }
  }
  return p;
}
console.log(sol(stmp, k));