1 Star 0 Fork 0

agony/LeetCode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
51.NQueens.Test.cs 1.99 KB
一键复制 编辑 原始数据 按行查看 历史
Kai Yang 提交于 2015-10-23 23:53 . 51. N-Queens
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using NUnit.Framework;
[TestFixture]
public class TestClass
{
[Test]
public void TestMethod()
{
for (var n = 1; n < 10; ++n)
{
var expectedResults = SolveNQueens(n);
var results = new Solution().SolveNQueens(n);
Assert.AreEqual(Normalize(expectedResults), Normalize(results));
}
}
private string Normalize(IList<IList<string>> results)
{
return JsonConvert.SerializeObject(results.OrderBy(r => JsonConvert.SerializeObject(r)));
}
private IList<IList<string>> SolveNQueens(int n)
{
var results = new List<IList<string>>();
var state = new List<int>();
Search(results, state, n);
return results;
}
private void Search(List<IList<string>> results, List<int> state, int n)
{
if (state.Count == n)
{
var result = new List<string>();
foreach (var s in state)
{
var sb = new StringBuilder();
for (var i = 0; i < s; ++i)
{
sb.Append('.');
}
sb.Append('Q');
for (var i = s + 1; i < n; ++i)
{
sb.Append('.');
}
result.Add(sb.ToString());
}
results.Add(result);
return;
}
for (var i = 0; i < n; ++i)
{
var valid = true;
for (var j = 0; j < state.Count; ++j)
{
if (state[j] - (state.Count - j) == i || state[j] + (state.Count - j) == i || state[j] ==i)
{
valid = false;
break;
}
}
if (valid)
{
state.Add(i);
Search(results, state, n);
state.RemoveAt(state.Count - 1);
}
}
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C#
1
https://gitee.com/agony2020/LeetCode.git
git@gitee.com:agony2020/LeetCode.git
agony2020
LeetCode
LeetCode
master

搜索帮助