Step-by-Step
[Java] Daily LeetCode Challenge 59. Spiral Matrix II 본문
https://leetcode.com/problems/spiral-matrix-ii/description/
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
흔한 시뮬레이션 문제
체감 난이도는 Easy같다.
for 문으로 일일이 지정해주는것보다 while문으로 증감 연산자 사용해주는게 더 가독성 좋고 효율적인거같다!
[코드]
class Solution {
public int[][] generateMatrix(int n) {
int[][] ans = new int[n][n];
int num = 1;
for(int i=0; i<n; i++)
ans[0][i]=num++;
int m = n, x=0, y=n-1;
while(m >= 1) {
m--;
// 아래
int cnt = m;
while(cnt-- > 0)
ans[++x][y]=num++;
// 왼
cnt = m;
while(cnt-- > 0)
ans[x][--y]=num++;
m--;
// 위
cnt = m;
while(cnt-- > 0)
ans[--x][y]=num++;
// 오
cnt = m;
while(cnt-- > 0)
ans[x][++y]=num++;
}
return ans;
}
}
'언어 > JAVA' 카테고리의 다른 글
[Java] Daily LeetCode Challenge 2466. Count Ways To Build Good Strings (0) | 2023.05.13 |
---|---|
[Java] Daily LeetCode Challenge 1035. Uncrossed Lines (0) | 2023.05.11 |
[Java] 백준 14567 - 선수과목 (0) | 2023.05.08 |
[Java] 백준 2565 - 전깃줄 (0) | 2023.05.08 |
LeetCode 1416. Restore The Array (0) | 2023.05.08 |
Comments