파이썬을 통한 모든 코드 시간 초과. 해당 코드를 자바로 바꿔서 제출했음. 확실히 타언어에 비해 수십배 느리단걸 다시 한번 느낌.

밑 코드 말고도 다른 유형으로 해보았지만 안됨. 파이썬 코드로 하지말고 애초부터 java나 C로 하는걸 추천. 빨리 풀고 다음 문제로 넘어가세요....

N = int(input())

res = 0
chess = [0] * N

def nqueen(cnt):
    global res
    
    if(cnt == N):
        res += 1
        return 0
    else:
        for i in range(N):
            chess[cnt] = i
            check = True
            for j in range(cnt):
                # 같은 열에 있는가
                if(chess[cnt] == chess[j]):
                    check = False
                # 대각의 관계에 있을 경우, 
                # 행의 거리와 열의 거리가 같다.
                if(abs(chess[cnt] - chess[j]) == cnt - j):
                    check = False
            
            if(check):
                nqueen(cnt + 1)
nqueen(0)
print(res)

단순히 위 코드를 변경한 자바 코드도 첨부합니다.

import java.util.Scanner;
 
public class Main {
    public static int N;
    public static int res;
    public static int[] chess;
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        N = sc.nextInt();
        chess = new int[N];
        
        nqueen(0);
        
        System.out.println(res);
    }
    
    public static void nqueen(int cnt){
        if(cnt == N){
            res++;
        } else{
            for(int i = 0; i < N; i++){
                chess[cnt] = i;
                boolean check = true;
                
                for(int j = 0; j < cnt; j++){
                    if(chess[cnt] == chess[j]){
                        check = false;
                    }
                    if(Math.abs(chess[cnt] - chess[j]) == cnt - j){
                        check = false;
                    }
                }
                if(check){
                nqueen(cnt + 1);
                }
            }
        }
    }
}

'# 코딩 문제 관련 > 파이썬' 카테고리의 다른 글

백준 14888번(python)  (0) 2020.01.02
백준 2580번(python)  (0) 2020.01.01
백준 15652번(python)  (0) 2019.12.31
백준 15651번(python)  (6) 2019.12.31
백준 15650번(python)  (0) 2019.12.31