문제

Write code that enhances all arrays such that you can call the snail(rowsCount, colsCount) method that transforms the 1D array into a 2D array organised in the pattern known as snail traversal order. Invalid input values should output an empty array. If rowsCount * colsCount !== nums.length, the input is considered invalid.

 

Snail traversal order starts at the top left cell with the first value of the current array. It then moves through the entire first column from top to bottom, followed by moving to the next column on the right and traversing it from bottom to top. This pattern continues, alternating the direction of traversal with each column, until the entire current array is covered. For example, when given the input array [19, 10, 3, 7, 9, 8, 5, 2, 1, 17, 16, 14, 12, 18, 6, 13, 11, 20, 4, 15] with rowsCount = 5 and colsCount = 4, the desired output matrix is shown below. Note that iterating the matrix following the arrows corresponds to the order of numbers in the original array.

https://leetcode.com/problems/snail-traversal/

 

예시

코드

/**
 * @param {number} rowsCount
 * @param {number} colsCount
 * @return {Array<Array<number>>}
 */
Array.prototype.snail = function(rowsCount, colsCount) {
    if(rowsCount * colsCount !== this.length) return [];
    
    const arr = Array.from(new Array(rowsCount), () => new Array(colsCount).fill(0));
    
    // 하, 우, 상, 우
    const dx = [1, 0, -1, 0];
    const dy = [0, 1, 0, 1];
    
    let x = -1;
    let y = 0;
    let d = 0; 
    let idx = 0;
    
    while(idx !== this.length){
        
        let nx = x + dx[d % 4];
        let ny = y + dy[d % 4];
        
        if(nx >= rowsCount || nx < 0 ){
            d++;
        }
        else {
            x = nx;
            y = ny;
            arr[x][y] = this[idx++];
            
            // 방향이 오른쪽일 때는 바로 방향 바꿔주기
            if(d % 4 === 1 || d % 4 === 3){
                d++;
            }
        }
    };
    
    return arr;
    
    
}

/**
 * const arr = [1,2,3,4];
 * arr.snail(1,4); // [[1,2,3,4]]
 */

 

문제의 조건에 있듯이,

`rowsCount * colsCount !== nums.length` 일 때는 빈 배열을 리턴하였다. 그 후, `rowsCount`와 `colsCount`로 0으로 차있는 2차원 배열을 만들었다. `nums`에 있는 값들을 해당 2차원 배열에 채울 것인데, 순서가 아래 -> 오른쪽 -> 위 -> 오른쪽으로 채워진다. 따라서 `dx`와 `dy`를 하, 우, 상, 우 순으로 움질일 수 있도록 정의했고, arr의 인덱스를 의미하는 x와 y, dx와 dy의 인덱스를 의미하는 d(방향), nums의 인덱스를 의미하는 idx를 변수로 따로 정의했다.다음에 이동할 nx와 ny가 위 아래 범위를 넘어가면 방향을 바꾸어주었고, 범위 안에 있으면 arr에 값을 넣었다. 이때, 방향이 오른쪽이었을 경우 한 번만 값을 넣고 다시 방향을 바꾸어주어야 하기 때문에 방향을 확인해서 오른쪽이면 d를 1 추가하였다.

728x90

+ Recent posts