728x90
반응형
https://leetcode.com/problems/spiral-matrix-ii/submissions/
참고자료
https://and-some.tistory.com/899
int n이 주어지면 n*n의 나선형 매트릭스를 만든다.
class Solution {
public int[][] generateMatrix(int n) {
int[][] arr = new int[n][n];
int rowStart=0;
int rowEnd=n-1;
int colStart=0;
int colEnd=n-1;
int tmp=1;
while(rowStart<=rowEnd && colStart<=colEnd){
for(int j=colStart; j<=colEnd;j++){
arr[rowStart][j]=tmp++;
}
rowStart++;
for(int i=rowStart;i<=rowEnd;i++){
arr[i][colEnd]=tmp++;
}
colEnd--;
if(rowStart<=rowEnd){
for(int i=colEnd; i>=colStart; i--){
arr[rowEnd][i]=tmp++;
}
}
rowEnd--;
if(colStart<=colEnd){
for(int i=rowEnd; i>=rowStart;i--){
arr[i][colStart]=tmp++;
}
}
colStart++;
}
return arr;
}
}
class Solution {
public int[][] generateMatrix(int n) {
int[][] arr = new int[n][n];
int rowStart=0;
int rowEnd=n-1;
int colStart=0;
int colEnd=n-1;
int cnt=0;
while(rowStart<=rowEnd && colStart<=colEnd){
for(int i=colStart; i<=colEnd;i++){
arr[rowStart][i]=++cnt;
}
rowStart++;
for(int i=rowStart; i<=rowEnd; i++){
arr[i][colEnd]=++cnt;
}
colEnd--;
for(int i=colEnd; i>=colStart; i--){
arr[rowEnd][i]=++cnt;
}
rowEnd--;
for(int i=rowEnd; i>=rowStart; i--){
arr[i][colStart]=++cnt;
}
colStart++;
}
return arr;
}
}
+) 세련된 풀이
1. 탈출 조건 : while(rowStart<=rowEnd && colStart<=colEnd)
2. for문 조건 :
//left
for (int i = colEnd; i >= colStart; i --) {
if (rowStart <= rowEnd)
matrix[rowEnd][i] = num ++;
}
rowEnd --;
//up
for (int i = rowEnd; i >= rowStart; i --) {
if (colStart <= colEnd)
matrix[i][colStart] = num ++;
}
colStart ++;
class Solution {
public static int[][] generateMatrix(int n) {
// 1
int[][] matrix = new int[n][n];
if (n == 0) return matrix;
int rowStart = 0;
int rowEnd = n-1;
int colStart = 0;
int colEnd = n-1;
int num = 1;
//2
while (rowStart <= rowEnd && colStart <= colEnd) {
//right
for (int i = colStart; i <= colEnd; i ++) {
matrix[rowStart][i] = num ++;
}
rowStart ++;
//down
for (int i = rowStart; i <= rowEnd; i ++) {
matrix[i][colEnd] = num ++;
}
colEnd --;
//left
for (int i = colEnd; i >= colStart; i --) {
if (rowStart <= rowEnd)
matrix[rowEnd][i] = num ++;
}
rowEnd --;
//up
for (int i = rowEnd; i >= rowStart; i --) {
if (colStart <= colEnd)
matrix[i][colStart] = num ++;
}
colStart ++;
}
return matrix;
}
}
728x90
반응형
'Java > Java 알고리즘 LeetCode' 카테고리의 다른 글
[LeetCode- Part. 1] 6. 최소 경로 합 # (0) | 2022.11.08 |
---|---|
[LeetCode- Part. 1] 5. 단어 나누기 # (+DP) (0) | 2022.11.05 |
[LeetCode- Part. 1] 3. 총길이 60초짜리 음악 쌍 (0) | 2022.11.04 |
[LeetCode- Part. 1] 2. 2행N열 재구성 (+ 2차원 배열 정렬) (0) | 2022.11.04 |
[LeetCode- Part. 1] 1. 가장 바깥 괄호제거 (+ StringBuilder, substring) (0) | 2022.11.04 |