259. 정수를 나선형으로 배치하기

김해준's avatar
Jan 13, 2026
259. 정수를 나선형으로 배치하기

사용언어 : Java

문제
notion image
notion image
풀이
using System; public class Solution { public int[,] solution(int n) { int[,] answer = new int[n,n]; int top = 0; int bottom = n - 1; int left = 0; int right = n -1; int num = 1; while(num <= n * n) { for(int i = left; i <= right; i++) { answer[top,i] = num; num++; } top++; for(int i = top; i <= bottom; i++) { answer[i,right] = num; num++; } right--; for(int i = right; i >= left; i--) { answer[bottom,i] = num; num++; } bottom--; for(int i = bottom ; i >= top;i-- ) { answer[i,left] = num; num++; } left++; if(num > n*n) break; } return answer; } }
notion image
Share article