代码拉取完成,页面将自动刷新
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);
}
}
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。