넓은 텃밭 만들기!

WooBuntu·2020년 9월 2일
0

JS 100제

목록 보기
30/34

넓은 텃밭 만들기!

const totalArea = [
  [0, 0, 0, 0, 0],
  [0, 1, 0, 0, 0],
  [0, 1, 0, 0, 0],
  [0, 0, 1, 0, 0],
  [0, 0, 0, 1, 0],
];

function markArea(area) {
  const reversed = area.map((row, idxOfRow) => {
    return row.map((current, idxOfCol) => {
      if (current == 0) {
        return 1;
      }
      return 0;
    });
  });

  let max = 1;
  let maxCoordinates = [];
  for (let row = 1; row < reversed.length; row++) {
    for (let col = 1; col < reversed.length; col++) {
      const current = reversed[row][col];
      const left = reversed[row][col - 1];
      const top = reversed[row - 1][col];
      const standard = reversed[row - 1][col - 1];
      if (current != 0) {
        reversed[row][col] = Math.min(standard, Math.min(left, top)) + 1;
        if (reversed[row][col] > max) {
          max = reversed[row][col];
          maxCoordinates[0] = row;
          maxCoordinates[1] = col;
        }
      }
    }
  }
  for (let i = maxCoordinates[0] - max + 1; i <= maxCoordinates[0]; i++) {
    for (let j = maxCoordinates[1] - max + 1; j <= maxCoordinates[1]; j++) {
      area[i][j] = "#";
    }
  }
  return area.map((row) => row.join("")).join("\n");
}

console.log(markArea(totalArea));
  • 동적 프로그래밍 연습 문제

0개의 댓글