[프로그래머스 lev2/JS] 행렬 테두리 회전하기

woolee의 기록보관소·2022년 12월 4일
0

알고리즘 문제풀이

목록 보기
116/178

문제 출처

프로그래머스 lev2 - 행렬 테두리 회전하기

나의 풀이

// 1. 행렬을 생성해준다.
// 2. 시계 방향으로 정직하게 while문을 일일이 돌아준다.

function solution(rows, columns, queries) {
  let answer = [];
  let matrix = Array.from({length:rows}, () => Array.from({length:columns}, () => 0));
  let s = 1;

  // 1. 
  matrix.map(v => {
    v.map((_, j) => v[j] = s+j);
    s = v[columns-1]+1;
  })

  // 2. 
  queries.map(v => {
    let clockWise = [];

    let y = v[0]-1;
    let x = v[1]-1;
    clockWise.push(matrix[y][x]);
    
    while(x !== v[3]-1) {
      // x++;
      clockWise.push(matrix[y][++x]);
      matrix[y][x] = clockWise[clockWise.length-2];
    }
    
    while(y !== v[2]-1) {
      // y++;
      clockWise.push(matrix[++y][x]);
      matrix[y][x] = clockWise[clockWise.length-2];
    }

    while(x !== v[1]-1) {
      // x--;
      clockWise.push(matrix[y][--x]);
      matrix[y][x] = clockWise[clockWise.length-2];
    }

    while(y !== v[0]-1) {
      // y--;
      clockWise.push(matrix[--y][x]);
      matrix[y][x] = clockWise[clockWise.length-2];
    }

    // console.log(matrix, clockWise);
    clockWise.sort((a,b) => a-b);
    answer.push(clockWise[0]);
  })
  return answer;
}

console.log(
  solution(6, 6, [
    [2, 2, 5, 4],
    [3, 3, 6, 6],
    [5, 1, 6, 3],
  ])
);

다른 풀이

function solution(rows, columns, queries) {
  const a = [...Array(rows)].map((_, r)=>[...Array(columns)].map((_, c)=>r*columns+c+1));
  const mins = [];

  queries.map(query => {
      const [x1, y1, x2, y2] = query.map(_=>_-1);
      let min = a[x1][y1], tmp = a[x1][y1];

      for(let i=x1;i<x2;i++) {
          a[i][y1] = a[i+1][y1];
          min = Math.min(min, a[i][y1]);
      }
      for(let i=y1;i<y2;i++) {
          a[x2][i] = a[x2][i+1];
          min = Math.min(min, a[x2][i]);
      }
      for(let i=x2;i>x1;i--) {
          a[i][y2] = a[i-1][y2];
          min = Math.min(min, a[i][y2]);
      }
      for(let i=y2;i>y1;i--) {
          a[x1][i] = a[x1][i-1];
          min = Math.min(min, a[x1][i]);
      }
      a[x1][y1+1] = tmp;

      mins.push(min);
  })

  return mins;
}
profile
https://medium.com/@wooleejaan

0개의 댓글