Algorithm/COS PRO 1급 기출문제

[COS PRO 1급 기출문제 - Java] 1-5 소용돌이 수

goakgoak 2020. 12. 20. 19:43

edu.goorm.io/learn/lecture/17301/cos-pro-1%EA%B8%89-%EA%B8%B0%EC%B6%9C%EB%AC%B8%EC%A0%9C-java/lesson/839399/1%EC%B0%A8-%EB%AC%B8%EC%A0%9C5-%EC%86%8C%EC%9A%A9%EB%8F%8C%EC%9D%B4-%EC%88%98-java

 

goorm

구름은 클라우드 기술을 이용하여 누구나 코딩을 배우고, 실력을 평가하고, 소프트웨어를 개발할 수 있는 클라우드 소프트웨어 생태계입니다.

www.goorm.io

 

문제 유형

solution 함수 구현

 

문제

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.*;
 
class Main {
    public int solution(int n) {
        int answer = 0;
        // 소스 코드를 입력하세요.
      return answer;
    }
    
    public static void main(String[] args) {        Main sol = new Main();
        int n1 = 3;
        int ret1 = sol.solution(n1);
 
        
        System.out.println("solution 함수의 반환 값은 " + ret1 + " 입니다.");
        
        int n2 = 2;
        int ret2 = sol.solution(n2);
 
        System.out.println("solution 함수의 반환 값은 " + ret2 + " 입니다.");
    }
}
cs

 

풀이

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.util.*;
 
class Main {
    int[] dx = {0,1,0,-1};
    int[] dy = {1,0,-1,0};
    
    public int solution(int n) {
        int answer = 0;
                int[][] soyongdoli = new int[n][n];
            
                int turn = (n%2 == 0)? n/2: (n/2 + 1);
            
                int cx, cy, nx, ny;            
                int cur = 1;
                for(int i = 0; i< turn; i++){
                    int d = 0;
                    cx = i;
                    cy = i;
                    soyongdoli[cx][cy] = cur++;
                    
                    while(d < 4){
                      int nx = cx + dx[d];
                        int ny = cy + dy[d];
                        
                        if(nx >= n || nx < 0 || ny >= n || ny < 0 || soyongdoli[nx][ny] > 0){
                            d++;
                            continue;
                        }
                        
                        soyongdoli[nx][ny] = cur++;
                        cx = nx;
                        cy = ny;
                    }
                }
            
//            print(soyongdoli);
            answer = getResult(soyongdoli);
      return answer;
    }
 
    
    public int getResult(int[][] arr){
        int sum = 0;
        for(int i = 0; i<arr.length; i++){
                sum += arr[i][i];
        }
        return sum;
    }
    
    public void print(int[][] arr){
        for(int i = 0; i<arr.length; i++){
            for(int j = 0; j<arr[i].length; j++){
                System.out.print(arr[i][j] + " ");
            }
            System.out.println();
        }
    }
cs