Hi, There!
안녕하세요, 바오밥입니다.
목차
- 문제
- 풀이
문제
문제 내용
https://school.programmers.co.kr/learn/courses/30/lessons/181832
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
풀이
나의 풀이
class Solution {
public int[][] solution(int n) {
int[][] answer = new int[n][n];
int cnt = 1;
int colStart = 0;
int colEnd = n-1;
int rowStart = 0;
int rowEnd = n-1;
while(cnt<=n*n) {
for(int i=colStart; i<=colEnd; i++) answer[rowStart][i] = cnt++; // right
rowStart++;
for(int i=rowStart; i<=rowEnd; i++) answer[i][colEnd] = cnt++; // down
colEnd--;
for(int i=colEnd; i>=colStart; i--) answer[rowEnd][i] = cnt++; // left
rowEnd--;
for(int i=rowEnd; i>=rowStart; i--) answer[i][colStart] = cnt++; // up
colStart++;
}
return answer;
}
}
다른 사람의 풀이
class Solution {
public int[][] solution(int n) {
int[][] answer = new int[n][n];
int num = 1;
int x = 0, y = 0;
int dx[] = {0, 1, 0, -1};
int dy[] = {1, 0, -1, 0};
int direction = 0;
while (num <= n * n) {
answer[x][y] = num++;
int nx = x + dx[direction];
int ny = y + dy[direction];
if (nx < 0 || nx >= n || ny < 0 || ny >= n || answer[nx][ny] != 0) {
direction = (direction + 1) % 4; //범위 밖에 나갔을 때 방향전환
nx = x + dx[direction];
ny = y + dy[direction];
}
x = nx;
y = ny;
}
return answer;
}
}
// right-> down -> left -> up 이동 경로를 dx, dy에 각각 저장해 순서대로 반복하는 알고리즘
Reference
[프로그래머스] Lv.0 정수를 나선형으로 배치하기.java
출처: 프로그래머스 코딩 테스트 연습, https://school.programmers.co.kr/learn/challenges
velog.io
'Dev > PS' 카테고리의 다른 글
[프로그래머스-코딩 기초 트레이닝] 정사각형으로 만들기 (0) | 2023.07.29 |
---|---|
[프로그래머스-코딩 기초 트레이닝] 특별한 이차원 배열 2 (0) | 2023.07.29 |
[프로그래머스-코딩 기초 트레이닝] 특별한 이차원 배열 1 (0) | 2023.07.28 |
[프로그래머스-코딩 기초 트레이닝] l로 만들기 (0) | 2023.07.28 |
[프로그래머스-코딩 기초 트레이닝] 조건에 맞게 수열 변환하기 3 (0) | 2023.07.28 |