이 글은 N-Queen 문제를 통해 Backtracking에 대한 핵심을 이해하고 활용하는 것을 다루고 있습니다.
N-Queen 문제는 N x N 크기의 체스판 위에 N개의 퀸(Queen)을 서로 서로 공격하지 않도록 배치하는 경우의 수를 찾는 고전적인 백트래킹(Backtracking) 문제입니다.
시도: 퀸을 배치한다
성공하면:
다음 행으로 이동
실패하면:
배치 취소 (백트래킹)
다음 위치에 퀸을 다시 시도
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
void SolveNQueen(int CurrentRow, vector<vector<bool>>& Board, bool& bHasSolution)
{
int Size = Board.size();
for (int Col = 0; Col < Size; ++Col)
{
bool bCanPlace = true;
// 위쪽 행들만 검사하면 충분
for (int Row = 0; Row < CurrentRow; ++Row)
{
if (Board[Row][Col] || // 같은 열
(Col - (CurrentRow - Row) >= 0 && Board[Row][Col - (CurrentRow - Row)]) || // 좌상 대각선
(Col + (CurrentRow - Row) < Size && Board[Row][Col + (CurrentRow - Row)])) // 우상 대각선
{
bCanPlace = false;
break;
}
}
if (!bCanPlace)
continue;
// 배치 시도
Board[CurrentRow][Col] = true;
if (CurrentRow == Size - 1)
{
bHasSolution = true;
for (const auto& Row : Board)
{
for (bool Cell : Row)
cout << (Cell ? "* " : "- ");
cout << '\n';
}
cout << '\n';
}
else
{
SolveNQueen(CurrentRow + 1, Board, bHasSolution);
}
// 백트래킹
Board[CurrentRow][Col] = false;
}
}
int main()
{
int N;
cout << "Enter the number of queens: ";
cin >> N;
vector<vector<bool>> Board(N, vector<bool>(N, false));
bool bHasSolution = false;
SolveNQueen(0, Board, bHasSolution);
if (!bHasSolution)
cout << "There is no solution!" << endl;
}