(C#) 백준 9663번 N-Queen (퀸 배치 문제)

2024. 2. 18. 16:59문제 풀기

https://www.acmicpc.net/problem/9663

using System.Text;
using System.Linq;

int size = int.Parse(Console.ReadLine());
int result = 0;
Calculate(0, ref result, new Map(size));
Console.WriteLine(result);

void Calculate(int pointCount, ref int result, Map map)
{
    if (pointCount == size)
    {
        result++;
        return;
    }

    for (int i = 0; i < size; i++)
    {
        if (CanDeposit(i))
        {
            Map childMap = new Map(size);
            childMap.CopyPoints(map.points);
            childMap.points[pointCount] = i;
            Calculate(pointCount + 1, ref result, childMap);
        }
    }

    bool CanDeposit(int i)
    {
        if (pointCount == 0) return true;
        
        for (int j = pointCount - 1; j >= 0; j--)
        {
            if (map.points[j] == i) return false;
        }

        int sideLength = 0;
        for (int j = pointCount - 1; j >= 0; j--)
        {
            sideLength++;
            if (map.points[j] == i + sideLength) return false;
            if (map.points[j] == i - sideLength) return false;
        }

        return true;
    }
}

public struct Map
{
    public int[] points;
    public int pointCount;

    public Map(int size)
    {
        this.points = new int[size];
        this.pointCount = 0;
    }

    public void CopyPoints(int[] points)
    {
        for (int i = 0; i < points.Length; i++) 
        {
            this.points[i] = points[i];
        }
    }
}

이것도 재귀적인 방식으로 풀어봤습니다.

'문제 풀기' 카테고리의 다른 글

(C#) 백준 14502번 : 연구소 (BFS)  (0) 2024.02.18
(C#) 백준 7569 : 토마토 (BFS)  (1) 2024.02.18
(c#) 백준 2447 별찍기  (0) 2024.02.18