📄 皇后.txt
字号:
using System;
using System.Collections.Generic;
using System.Text;
namespace 皇后问题
{
public class Queen
{
public static int Main()
{
int board_size = 0,x=0,y=0;//棋盘大小,当前行,当前列
uint solution_count = 0; //皇后摆放方案的个数
int[] rows, cols, slot1, slot2, x2y;//行占用情况,列占用情况,“/”状斜线占用情况,“\”状斜线占用情况,皇后坐标
string judge;
DateTime t_start, t_end;
do
{
Console.WriteLine("请输入棋盘的大小");
board_size = Convert.ToInt32(Console.ReadLine());//指定的数字转换为32位有符号整数
while (board_size <= 0)
{
Console.WriteLine("非法数据,所输入数据必须大于0,请重新输入:");
board_size = Convert.ToInt32(Console.ReadLine());
}
rows = new int[board_size];
cols = new int[board_size];
slot1 = new int[board_size * 2 - 1];
slot2 = new int[board_size * 2 - 1];
x2y = new int[board_size];
for (int i = 0; i < board_size; i++)
x2y[i] = -1; //坐标初始化都为-1
t_start = DateTime.Now;
while (true)
{
for (y = x2y[x] + 1; y < board_size; y++)//找到第y列的插入点
if (rows[x] == 0 && cols[y] == 0 && slot1[x + y] == 0 && slot2[x - y + board_size - 1] == 0)
break;
if (y < board_size)
{
//第X行的棋子落下
rows[x] = 1; cols[y] = 1; slot1[x + y] = 1; slot2[x - y + board_size - 1] = 1; x2y[x] = y;
}
else
{
//回溯,拿起棋子
if (x > 0)
{
x2y[x] = -1;
x--;
rows[x] = 0; cols[x2y[x]] = 0; slot1[x + x2y[x]] = 0; slot2[x - x2y[x] + board_size - 1] = 0;
continue;
}
else break;
}
if (x == board_size - 1) //如果已经得到了一组解,即当最后一行棋子落定之时
{
for (int i = 0; i < board_size; i++)
{
for (int j = 0; j < board_size; j++)
{
if (x2y[i] == j) Console.Write("Q");
else Console.Write("■");
}
Console.Write("\n");
}
Console.Write("\n");
solution_count++; //总方案数加一
rows[x] = 0; cols[x2y[x]] = 0; slot1[x + x2y[x]] = 0; slot2[x - x2y[x] + board_size - 1] = 0;//放弃这一列
}
else
{
x++; //继续处理下一行
}
}
t_end = DateTime.Now;
Console.WriteLine("总共{0}组解", solution_count);
Console.WriteLine("计算及打印共用时间{0}秒", t_end - t_start);
Console.WriteLine("是否还要继续?y/n");
judge = Console.ReadLine();
} while (judge == "y");
return 0;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -