C#-N皇后

using System;
using System.Collections.Generic;
namespace N皇后
{
	class Program
	{
		public static List<List<string>> Qdeen(int n)
		{
			List<List<string>> res = new List<List<string>>();
			List<string> map = new List<string>();
			int[,] attack = new int[n, n];
			Track(attack, map,res);
			return res;
		}
		static void setAttack(int x,int y,int[,] attack, List<string> map)
		{
			string temp = "";
			int n = attack.GetLength(0);
			for (int i = 0; i < n; i++)
			{
				temp += i == y ? 'Q' : 'T';
			}
			map.Add(temp);
			int[] dx = new int[] { -1, 0, 1, 1, 1, 0, -1, -1 };
			int[] dy = new int[] { 1, 1, 1, 0, -1, -1, -1, 0 };
			for (int i = 1; i < n; i++)
			{
				for (int j = 0; j < dx.Length; j++)
				{
					if(x + dx[j] * i>=0&& x + dx[j] * i<n&& y + dy[j] * i>=0&&y + dy[j] * i<n)
					attack[x + dx[j] * i, y + dy[j] * i] = 1;
				}
			}
		}
		static void Track(int[,] attack, List<string> map, List<List<string>> res)
		{
			int n = attack.GetLength(0);
			int index = map.Count;
			if (index == n)
			{
				res.Add(new List<string>(map));
				return ;
			}
			for (int i = 0; i < n; i++)
			{
				if (attack[index, i] != 0) continue;			
				int[,] temp = (int[,])attack.Clone();
				setAttack(index, i, attack,map);
				Track(attack, map,res);
				attack = temp;
				map.RemoveAt(index);
			}
		}
		static void Main(string[] args)
		{
			int n = int.Parse(Console.ReadLine());
			List<List<string>> res = Qdeen(n);
			foreach (var item in res)
			{
				foreach (var sub in item)
				{
					Console.WriteLine(sub);
				}
				Console.WriteLine("------------------");
			}
			Console.WriteLine(res.Count);
		}
	}
}

几点心得

  1. 只要不在之前的攻击范围摆上“皇后”,之后的皇后攻击范围也不会包含之前“皇后的位置”
  2. map的列表对象,给其他结果赋值,如果之后map值发生变化,那么结果也会发生变化。所以结果赋值时要新建一个值与map一致的列表对象。
  3. 确定攻击范围:虽然规则是,皇后的攻击范围是横竖斜,但是这种规则不便于编码。
    所以可以认为是,以自身位置为原点,向八个方向扩散。
    int[] dx = new int[] { -1, 0, 1, 1, 1, 0, -1, -1 };
    int[] dy = new int[] { 1, 1, 1, 0, -1, -1, -1, 0 };
for (int i = 1; i < n; i++)//扩散次数
			{
				for (int j = 0; j < dx.Length; j++)
				{
					if(x + dx[j] * i>=0&& x + dx[j] * i<n&& y + dy[j] * i>=0&&y + dy[j] * i<n)
					attack[x + dx[j] * i, y + dy[j] * i] = 1;
				}
			}
  1. 数组的初始化:也就是深浅拷贝
    浅拷贝共用相同的引用对象int[,] temp = attack;
    深拷贝只是两者类型和值一致的两个不同对象:int[,] temp = (int[,])attack.Clone();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值