본문 바로가기
Dev/Java

크기가 [n][n]인 2차원 배열 가장자리부터 1,2,3,4,......로채우기

by 펭귄안에 온천 2023. 8. 6.
728x90
반응형
    public int[][] solution(int n) {
        int[][] answer = new int[n][n];
        for(int i=0; i<n; i++){
            Arrays.fill(answer[i],0);
        }
        int[][] move = {
                {0,1},{1,0},{0,-1},{-1,0}
                // 순서는 오른쪽, 아래, 왼쪽, 위쪽
        };
        int index=1;
        int x=0;
        int y=0;
        int dir = 0;
        while (index<=n*n){
            answer[x][y] = index;
            int nextX = x+move[dir][0];
            int nextY = y+move[dir][1];
            if( nextX >= n || nextX<0 ||
                nextY >= n || nextY<0 ||
                answer[nextX][nextY] != 0
            ){
                dir = (dir+1)%4;
                nextX = x+move[dir][0];
                nextY = y+move[dir][1];
            }
            x = nextX;
            y = nextY;
            index++;
        }
        return answer;
    }

result : 

[
    [1, 2, 3, 4],
    [12, 13, 14, 5],
    [11, 16, 15, 6],
    [10, 9, 8, 7]
]
반응형

'Dev > Java' 카테고리의 다른 글

Java에서 System.arraycopy를 사용하여 배열 복사하기  (0) 2023.08.07
String, StringBuilder, StringBuffer의 차이  (0) 2023.05.15
POJO 정리  (0) 2023.02.15
AOP 개인 저장용  (0) 2022.12.28
Java reflection Sample Code  (0) 2022.12.16