알고리즘/Backtracking

N Queen Problem

1minair 2022. 5. 10. 20:14
728x90
#include <iostream>
#define N 4
using namespace std;

void printSolution(int board[N][N])
{
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++)
            cout << " " << board[i][j] << " ";
        printf("\n");
    }
}

// promising function
bool isSafe(int board[N][N], int row, int col)
{
    // 현재 queen을 놓기 위해 안전한지 확인 -> 놓으려고 하는 위치 board[row][col]
    int i, j;

    for (i = 0; i < col; i++)   // 왼쪽 확인
        if (board[row][i])
            return false;
    
    for (i = row, j = col; i >= 0 && j >= 0; i--, j--)  // 왼쪽 대각 위 
        if (board[i][j])
            return false;
    
    for (i = row, j = col; j >= 0 && i < N; i++, j--)   // 왼쪽 대각 아래
        if (board[i][j])
            return false;

    return true;
}

bool solveNQUtil(int board[N][N], int col)
{
    if (col >= N) return true;

    for (int i = 0; i < N; i++) {   // i는 행 col은 열
        if (isSafe(board, i, col)) {
            board[i][col] = 1;
            if (solveNQUtil(board, col + 1))return true;
            board[i][col] = 0; // BACKTRACK
        }
    }
    return false;
}

bool solveNQ()
{
    int board[N][N] = { { 0, 0, 0, 0 },
                        { 0, 0, 0, 0 },
                        { 0, 0, 0, 0 },
                        { 0, 0, 0, 0 } };

    if (solveNQUtil(board, 0) == false) {
        cout << "Solution does not exist";
        return false;
    }

    printSolution(board);
    return true;
}

int main()
{
    solveNQ();
    return 0;
}

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

Knapsack  (0) 2022.05.11
Hamiltonian Circuits (HC) Problem  (0) 2022.05.08
Graph-coloring  (0) 2022.05.08
Subset Sum Problem  (0) 2022.05.08
Backtraking이란  (0) 2022.05.04