Algorithm
[cospro] 소용돌이 수
taeveloper
2022. 2. 18. 16:16
01 COS PRO 1급 JAVA 1차
100%
[1차] 문제5) 소용돌이 수 - JAVA
실습 내용
※ 프로그램 구현문제
□ 문제설명
다음과 같이 n x n 크기의 격자에 1부터 n x n까지의 수가 하나씩 있습니다.
![](https://blog.kakaocdn.net/dn/dCJsBJ/btrtGikYgh3/1aSWPAxVlEBQijxnMCQJdK/img.png)
이때 수가 다음과 같은 순서로 배치되어있다면 이것을 n-소용돌이 수라고 부릅니다.
![](https://blog.kakaocdn.net/dn/WJU4Z/btrtEwjgwjh/L0AYWjfrok3xNFSxu9d5uK/img.png)
소용돌이 수에서 1행 1열부터 n 행 n 열까지 대각선상에 존재하는 수들의 합을 구해야 합니다.
![](https://blog.kakaocdn.net/dn/bcevCD/btrtCo0iXZE/DM1sfyrVzfJNsvBmO7409k/img.png)
위의 예에서 대각선상에 존재하는 수의 합은 15입니다.
격자의 크기 n이 주어질 때 n-소용돌이 수의 대각선상에 존재하는 수들의 합을 return 하도록 solution 메소드를 완성해주세요.
□ 매개변수 설명
격자의 크기 n이 solution 함수의 매개변수로 주어집니다.
- n은 1 이상 100 이하의 자연수입니다.
□ return 값 설명
n-소용돌이 수의 대각선상에 존재하는 수들의 합을 return 해주세요.
□ 예시
n | return | |
예시 #1 | 3 | 15 |
예시 #2 | 2 | 4 |
□ 예시설명
예시 #1
문제의 예와 같습니다.
예시 #2
1과 3을 더하여 4가 됩니다.
![](https://blog.kakaocdn.net/dn/csvhHI/btrtBVYqK8K/ugCH9iP7wpL2N2d95GtzmK/img.png)
package com.example.codingtest.cospro.first;
public class 소용돌이수 {
public static void main(String[] args) {
int data1 = 3;
int data2 = 2;
System.out.println(solution(data1));
}
public static int solution(int n){
int answer = 0;
int[][] arr = new int[n][n];
int number = 1;
int x = 0;
int y = 0;
char direction = 'r';
for(int i = 0; i < n * n; i++){
arr[x][y] = number++;
switch (direction){
case 'r':
if(y + 1 < n && arr[x][y+1] == 0){
y++;
} else {
direction = 'd';
x++;
}
break;
case 'l':
if(y - 1 >= 0 && arr[x][y-1] == 0){
y--;
} else {
direction = 'u';
x--;
}
break;
case 'u':
if(x - 1 >= 0 && arr[x-1][y] == 0){
x--;
} else {
direction = 'r';
y++;
}
break;
case 'd':
if(x + 1 < n && arr[x+1][y] ==0){
x++;
} else {
direction = 'l';
y--;
}
break;
}
}
for(int i = 0; i < n; i++){
answer += arr[i][i];
}
return answer;
}
}