본문 바로가기

알고리즘

나선형 보드

https://school.programmers.co.kr/learn/courses/30/lessons/181832

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

기본적인 방향전환

class Solution {
    //동 남 서 북
    int[] di = {0,1,0,-1};
    int[] dj = {1,0,-1,0};
    public int[][] solution(int n) {
        int[][] board = new int[n][n];
        for(int i = 0; i<n; i++){
            for(int j = 0; j<n; j++){
                board[i][j] = 0;
            }
        }
        
        // 00 01 02 03
        // 13 23 33
        // 32 31 30
        // 20 10
        // 11 12
        // 22
        // 21
        
        // 00 01 02 03 04 
        // 14 24 34 44
        // 43 42 41 40
        // 30 20 10
        // 11 12 13
        // 23 33
        // 32 31
        // 21
        // 22
        
        //행
        int curI = 0;
        //열
        int curJ = 0;
        //방향 
        int dir = 0;
        board[0][0]=1;
        for(int curN = 2; curN<=n*n;){
        	//System.out.println("dir:"+dir);
            int nextI = curI + di[dir%4];
            int nextJ = curJ + dj[dir%4];
            if(nextI>-1 && nextI < n && nextJ > -1 && nextJ < n ){
                if(board[nextI][nextJ] == 0){
                    curI = nextI;
                    curJ = nextJ;
                    board[curI][curJ] = curN;
                    //System.out.println(curI+" "+curJ+" = "+curN);
                    curN++;
                }
                else{
                    dir++;
                }
            }
            else{
                dir++;
            }
        }
        
        return board;
    }
}

보드류는 미리 그려보고 할 것

'알고리즘' 카테고리의 다른 글

deque의 활용  (0) 2024.06.11
이진수 string 활용  (0) 2024.06.09
Character uppercase 사용법  (0) 2024.06.08
원하는 문자열 찾기  (0) 2024.06.08
배열의 원소 삭제하기  (0) 2024.06.08