トップページに戻る    次のC#のサンプルへ    前のC#のサンプルへ

8-7 8王妃問題

問題

Eight queens puzzleを解きます。


ソース

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        int[,] Ban = new int[9, 9];

        var stk = new Stack<int[,]>();
        stk.Push((int[,])Ban.Clone());

        int answerCnt = 0;
        while (stk.Count != 0) {
            Ban = stk.Pop();

            int ouhiCnt = 0;
            for (int X = 1; X <= 8; X++) {
                for (int Y = 1; Y <= 8; Y++) {
                    if (Ban[Y, X] == 1) ouhiCnt++;
                }
            }

            if (ouhiCnt == 8) {
                Console.WriteLine();
                Console.WriteLine("answer" + (++answerCnt).ToString());
                for (int Y = 1; Y <= 8; Y++) {
                    for (int X = 1; X <= 8; X++) {
                        Console.Write(Ban[Y, X]);
                    }
                    Console.WriteLine();
                }
                continue;
            }

            for (int Y = 1; Y <= 8; Y++) {
                if (IsValid(Ban, Y, ouhiCnt + 1)) {
                    int[,] cloneArr = (int[,])Ban.Clone();
                    cloneArr[Y, ouhiCnt + 1] = 1;
                    stk.Push(cloneArr);
                }
            }
        }
    }

    static bool IsValid(int[,] pBan, int targetY, int targetX)
    {
        //横チェック
        for (int X = 1; X <= 8; X++) {
            if (pBan[targetY, X] == 1)
                return false;
        }

        //左下チェック
        for (int X = targetX, Y = targetY;
             1 <= X && X <= 8 && 1 <= Y && Y <= 8;
             X--, Y++) {
            if (pBan[Y, X] == 1) return false;
        }

        //左上チェック
        for (int X = targetX, Y = targetY;
             1 <= X && X <= 8 && 1 <= Y && Y <= 8;
             X--, Y--) {
            if (pBan[Y, X] == 1) return false;
        }
        return true;
    }
}


実行結果

省略
answer91
10000000
00000010
00010000
00000100
00000001
01000000
00001000
00100000

answer92
10000000
00000010
00001000
00000001
01000000
00010000
00000100
00100000


解説

Stackジェネリックは強力ですねぇ