본문 바로가기
알고리즘 & 자료구조/프로그래머스

N Queen

by 신재권 2023. 3. 29.
package programmers;

public class N_Queen {

   private static int ans;
   private static int[] map;

   public static int solution(int n) {
      ans = 0;
      map = new int[n];

      go(0, n);

      return ans;
   }

   private static void go(int current, int n) {
      if (current == n) {
         ans++;
         return;
      }
      for (int i = 0; i < n; i++) {
         map[current] = i;
         if (check(current)) {
            go(current + 1, n);
         }
      }
   }

   private static boolean check(int i) {
      for (int j = 0; j < i; j++) {
         if (map[i] == map[j]) { //직선 상 위치
            return false;
         }
         if (Math.abs(i - j) == Math.abs(map[i] - map[j])) { //대각 위치
            return false;
         }
      }
      return true;
   }

   public static void main(String[] args) {
      System.out.println(solution(4));
   }
}

'알고리즘 & 자료구조 > 프로그래머스' 카테고리의 다른 글

조이스틱  (0) 2023.03.31
시소 짝꿍  (0) 2023.03.30
테이블 해시 함수  (0) 2023.03.28
혼자 놀기의 달인  (0) 2023.03.27
마법의 엘레베이터  (0) 2023.03.25