[Algorithms] 12. Matrix Spiral

7233 단어 AlgorithmsAlgorithms

문제


해결방법



1. results라는 빈 배열을 만든다
2. 1로 시작하는 counter 변수를 만든다
3. start coulmn <= end column && start row <= end row일 경우 for loop을 돈다 (while문 사용하기)
4. start coulmn과 end column으로 for loop을 한다
5. results[start_row][i] <- counter variable
6. increase counter++
7. increase start row
8. for loop -> start row to end row
9. results[i][end_column] <- counter variable
10. counter 증가++
11. decrement end column
12. 반복한다.

제출 코드


function matrix(n) {
  const results = [];
  
  for (let i = 0; i < n ; i++) {
    results.push([]);
  }
  
  let counter = 1;
  let startColumn = 0;
  let endColumn = n -1;
  let startRow = 0;
  let endRow= n-1;
  while (startColumn <= endColumn && startRow <= endRow) {
    // Top row
    for ( let i = startColumn; i <= endColumn; i++) {
      results[startRow][i]= counter;
      counter++;
    }
    startRow++;
    
    
    // Right coulmn
    for (let i = startRow; i <= endRow; i++) {
      results[i][endColumn] = counter;
      counter++;
    }
    endColumn--;
    
    // Bottom row
    for (let i = endColumn; i >= startColumn; i--) {
      results[endRow][i] = counter;
      counter++;
    } 
    endRow--;
    
    // start Column
    for (let i = endRow; i >=startRow; i--) {
      results[i][startColumn] = counter;
      counter++;
    }
    startColumn++;
  }
}

좋은 웹페이지 즐겨찾기