(1)

[Java] 59.Spiral Matrix II - LeetCode Daily Challenge

https://leetcode.com/problems/spiral-matrix-ii/ Spiral Matrix II - LeetCode Can you solve this real interview question? Spiral Matrix II - Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order. Example 1: [https://assets.leetcode.com/uploads/2020/11/13/spiraln.jpg] Input: n = 3 O leetcode.com 풀이 방향에 대한 변수와, 한 칸씩 체크해줄 변수를 지정해 준 뒤, 카운팅만 잘 해주면 되는 문제였..

[Java] 59.Spiral Matrix II - LeetCode Daily Challenge

P.S./leetcode 2023. 5. 10. 21:15
728x90
728x90

https://leetcode.com/problems/spiral-matrix-ii/

 

Spiral Matrix II - LeetCode

Can you solve this real interview question? Spiral Matrix II - Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.   Example 1: [https://assets.leetcode.com/uploads/2020/11/13/spiraln.jpg] Input: n = 3 O

leetcode.com

 

 

 

풀이


방향에 대한 변수와, 한 칸씩 체크해줄 변수를 지정해 준 뒤, 카운팅만 잘 해주면 되는 문제였다.

class Solution {		
	
    public int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];
        int top = 0;
        int bottom = n-1;
        int left = 0;
        int right = n-1;
        int cnt = 1;
        while(cnt <= n*n) {
        	for(int i=left; i<=right; i++) {
        		matrix[top][i] = cnt;
        		cnt++;
        	}
        	top++;
        	  
        	for(int i=top; i<=bottom; i++) {
        		matrix[i][right] = cnt;
        		cnt++;
        	}
        	right--;
        	
        	for(int i=right; i>=left; i--) {
        		matrix[bottom][i] = cnt;
        		cnt++;
        	}
        	bottom--;
        	
        	for(int i=bottom; i>=top; i--) {
        		matrix[i][left] = cnt;
        		cnt++;
        	}
        	left++;
        	
        }
        return matrix;
    }
}

 

 

728x90
300x250
mag1c

mag1c

2년차 주니어 개발자.

방명록