알고리즘

프로그래머스 N-Queen (JAVA)

박카스마시며코딩 2022. 9. 21. 16:44

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

 

프로그래머스

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

programmers.co.kr

 

저는 구현을 통해 문제를 해결하였습니다.

저는 좌표를 배열에 넣고 현재 좌표에 비교하여 현재 좌표에 넣을 수 있는지를 판단하고 다음 y좌표로 넘어갔습니다.

depth가 n이라면 n개의 queen을 놓은 것이기 때문에 1을 리턴 그러지 않고 y가 n이상이면 0을 리턴하도록 하였습니다.

 

class Solution {
    public static class Node{
        int y;
        int x;
        public Node(int y,int x){
            this.y = y;
            this.x = x;
        }
    }
    public int solution(int n) {
        int answer = 0;
        // answer = cal(0,0,0,map,check,n);
        Node[] visited = new Node[n];
        answer = cal(visited,0,0,n);
        return answer;
    }
    private static int cal(Node[] visited, int y,int depth, int n){
        if(depth == n){
            return 1;
        }
        if(y >= n){
            return 0;
        }
        int result = 0;
        for(int x = 0 ; x < n ; x++){
            if(!checkVisited(y,x,depth,visited)){
                visited[depth] = new Node(y,x);
                result += cal(visited,y+1,depth+1,n);
            }
        }
        return result;
    }
    private static boolean checkVisited(int y,int x,int depth,Node[] visited){
        for(int i = 0 ; i < depth ; i++){
            Node node = visited[i];
            if(Math.abs(y-node.y) == Math.abs(x-node.x)){
                return true;
            }
            if(y == node.y || x == node.x){
                return true;
            }
        }
        return false;
    }
}