๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

์ฝ”๋”ฉํ…Œ์ŠคํŠธ/LeetCode

[LeetCode] Rotate Image

๋ฌธ์ œ๋งํฌ

 

Rotate Image - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

์ฃผ์–ด์ง„ 2์ฐจ์› ๋ฐฐ์—ด์„ ์‹œ๊ณ„๋ฐฉํ–ฅ์œผ๋กœ ํšŒ์ „์‹œ์ผœ ๋ฐ˜ํ™˜ํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค
์ฃผ์˜์‚ฌํ•ญ : ์ƒˆ๋กœ์šด ๋ฐฐ์—ด์„ ๋งŒ๋“ค์ง€ ๋ง๊ณ  ๊ธฐ์กด ๋ฐฐ์—ด์„ ๋ณ€๊ฒฝ์‹œํ‚ค๋Š” ๋ฐฉํ–ฅ์œผ๋กœ ์ง„ํ–‰ํ•ด์•ผํ•œ๋‹ค.

์ ‘๊ทผ ๋ฐฉ๋ฒ•
ํ•œ๊ฐ€์ง€ ๊ทœ์น™์„ ๋ฐœ๊ฒฌํ•˜์˜€๋‹ค.

ํ–‰๋ ฌ์„ ๋Œ€๊ฐ์„ ์„ ๊ธฐ์ค€์œผ๋กœ swapํ•œ ๋’ค, ๋ชจ๋“  ํ–‰์„ ๋’ค์ง‘์œผ๋ฉด ์‹œ๊ณ„๋ฐฉํ–ฅ์œผ๋กœ ํšŒ์ „๋œ ํ–‰๋ ฌ์ด ๋ฐ˜ํ™˜๋œ๋‹ค.

        
1 3
4 5 6
7 8 9
 => ๋Œ€๊ฐ์„  ๊ธฐ์ค€์œผ๋กœ swap
1 4 7
2 5 8
3 6 9
=> swapํ•œ ํ–‰๋ ฌ์˜ row๋ฅผ reverse
7 4 1
8 5 2
9 6 3

์ด๋Ÿฌํ•œ ๊ณผ์ •์„ ๊ทธ๋Œ€๋กœ ์ฝ”๋“œ๋กœ ๋ณ€ํ™˜ํ•˜๋ฉด ๋œ๋‹ค.

1. ๊ธฐ์กด ๋ฐฐ์—ด์„ ๋Œ€๊ฐ์„  ๊ธฐ์ค€์œผ๋กœ swap
for(let i =0;i<row;i++){
    for(let j = i;j<col;j++){
        [matrix[i][j],matrix[j][i]] = [matrix[j][i],matrix[i][j]]
    }
}โ€‹


2. swapํ•œ ๋ฐฐ์—ด์„ row๋ฅผ ๊ธฐ์ค€์œผ๋กœ reverse()

for(i=0;i<row;i++){
    matrix[i].reverse();
}


 

/**
 * @param {number[][]} matrix
 * @return {void} Do not return anything, modify matrix in-place instead.
 */
var rotate = function(matrix) {
    let row = matrix.length;
    let col = matrix[0].length;
    
    for(let i =0;i<row;i++){
        for(let j = i;j<col;j++){
            [matrix[i][j],matrix[j][i]] = [matrix[j][i],matrix[i][j]]
        }
    }
    
    for(i=0;i<row;i++){
        matrix[i].reverse();
    }
    
    return matrix;
};

'์ฝ”๋”ฉํ…Œ์ŠคํŠธ > LeetCode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[LeetCode] Numbers With Same Consecutive Differences  (0) 2022.09.03
[LeetCode] Reduce Array Size to The Half  (0) 2022.08.18
[LeetCode] Unique Morse Code Words  (0) 2022.08.17
[LeetCode] Combination Sum IV  (0) 2022.08.05
[LeetCode] My Calendar I  (0) 2022.08.03