找到我可以在4 * 4棋盘中放置4个皇后的地方?

时间:2011-01-02 20:11:31

标签: algorithm

我不是要求解决方案。我想要所有可能的展示位置。

2 个答案:

答案 0 :(得分:6)

有两种方法可以在4x4棋盘上放置四个皇后,这样任何一个皇后都不会攻击任何其他棋子:

_ ♕ _ _    _ _ ♕ _
_ _ _ ♕    ♕ _ _ _
♕ _ _ _    _ _ _ ♕
_ _ ♕ _    _ ♕ _ _

Source

<强>算法

我不打算给你代码,但我可以告诉你算法应该如何工作。要找到解决方案,您可以使用带回溯的强力算法。

  • 对于每一行,尝试在该行的第一个免费squre中放置一个女王,然后移动到下一行。
  • 如果没有可用的方格,至少有一位女王在错误的位置。
  • 返回上一行并将女王移动到下一个可用的方格。
  • 重复直到找到解决方案。

以下是该算法如何适用于4x4电路板:

♕ _ _ _
_ _ _ _
_ _ _ _
_ _ _ _

第二行的女王不能进入第一列或第二列,因为它们都受到了攻击,所以试试第三行:

♕ _ _ _
_ _ ♕ _
_ _ _ _
_ _ _ _

现在是第三行......没有空格可用。回溯并尝试第二行的新位置。

♕ _ _ _
_ _ _ ♕
_ _ _ _
_ _ _ _

现在我们可以放置第三排女王:

♕ _ _ _
_ _ _ ♕
_ ♕ _ _
_ _ _ _

第四排没有运气。我们已经尝试了第三行的每个位置,第二行,所以回溯到第一行:

_ ♕ _ _
_ _ _ _
_ _ _ _
_ _ _ _

等...

祝你好运!

答案 1 :(得分:0)

以下代码在C#中。希望它有所帮助

    static void Main(string[] args)
    {
        Program obj = new Program();
        StreamWriter saveText = new StreamWriter("Output.txt",true);
        obj.fourQueen(0, 0, 4, "");
        Console.Read();

    }


    public void fourQueen(int r , int c, int queensLeft, string onePlacement){
        if(queensLeft == 0){
            //onePlacement may not be a answer
            Console.WriteLine(onePlacement);
        return ;

        }

        if(c==4){
            //If I have reached the end of 1 row, go to next one
            c=0;
            r=r+1;
        }
        if(r==4){
            //I have considered all rows and still not put all queens. cannot be a solution
            return;
        }
        int te = queensLeft - 1;






        int newcol = c + 1;
        fourQueen(r,newcol,te,onePlacement+"| ("+r+","+c+")|");
        //Note: As i am placing queen in (r,c) above, there is no point in continuing //recursive call from r,c+1 as cannot place another in same row. I should
        //go from  r+1,0
        fourQueen(r,newcol,queensLeft,onePlacement);


    }
}

}