zoukankan      html  css  js  c++  java
  • 回溯实现八皇后问题(C#)

    以下利用回溯解决八皇后问题。总共有92种结果。 PrintQueen 是打印函数,isConfict 是用来判断是否冲突(在同一直线和斜线则有冲突)

    EightQueen 为主函数,

    算法思路: 先把第一个皇后放在(0,0)的位置。然后从第一行往下找,如果成功,则继续往下探索。一直到第八行,然后回溯。

    如果回溯到第一行,说明第一个皇后在(0,0)的所有情况全部已经列出。接着遍历(0,1)一直到(0,7)

    public class Program

    {

    static int count = 0;

    static int[] chess = new int[8]{-1,-1,-1,-1,-1,-1,-1,-1};

    static void PrintQueen()

    {

    Console.WriteLine(string.Format("========{0}==============", count));

    for (int i = 0; i < 8; i++)

    {



    int m = 0;

    int n = chess[i] + 1;

    while (m < chess[i])

    {

    Console.Write("* ");

    m++;

    }

    Console.Write("@ ");

    while (n < 8)

    {

    Console.Write("* ");

    n++;

    }

    Console.WriteLine("");



    }

    Console.WriteLine("=======================");

    }



    static bool isConfict(int x2, int y2)

    {

    int x1, y1;

    for (int i = 0; i < x2; i++)

    {

    x1 = i;

    y1 = chess[i];

    if (y1 == y2 || (x1 - y1 == x2 - y2) || (x1 + y1 == x2 + y2))

    return true;

    }

    return false;

    }



    static void EightQueen()

    {

    int column = 0;

    int i = 0;

    int t = 0;

    int k = 0;

    int z = 0;

    while (column < 8)

    {

    chess[0] = column;

    int m;

    for (m = t; m < 8; m++)

    {

    k = i + 1;

    chess[k] = m;

    if (isConfict(k, m))//冲突就停止

    {

    continue;

    }

    else

    {

    z = m + 1; //保存上次找到的合法位置,以备回溯的时候当做起点。

    i++;

    m = -1;

    }

    if (i >= 7) // 成功也要回溯

    {

    count++;

    PrintQueen();

    i--;// 回溯

    m = z;

    continue;

    }

    if (i <= 0) // 如果回溯到了第一行,column++

    {

    column++;

    i = 0; t = 0; k = 0;

    break;

    }

    }

    if (m >= 8 ) //失败

    {

    t = chess[i + 1] + 1;

    if (t == 8)

    {

    i--; // 回溯到上一层

    }

    }

    if (i < -1)

    break;



    }

    Console.WriteLine("Done");

    }

    static void Main()

    {

    EightQueen();

    }

    }
  • 相关阅读:
    vue中select设置默认选中
    验证码
    JS图片src转义
    int main(int argc, char** argv) 以及CommandLineParser
    Visual Studio2013 配置opencv3.3.0 x64系统
    ubuntu16.04 下安装 visual studio code 以及利用 g++ 运行 c++程序
    第三次作业
    第二次作业
    作业一
    第四次作业
  • 原文地址:https://www.cnblogs.com/zhangjiang/p/2396119.html
Copyright © 2011-2022 走看看