空闲时间写了经典的八皇后程序。没有参考标准答案。百分百原创,虽然不是最佳解法,但是留个纪念
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.OleDb;
using System.Data;
using System.IO;
namespace ConsoleApplication2
{
public class Program
{
static void Main(string[] args)
{
List<List<int>> map = IniteMap();
FindWay(map, 0);
Console.ReadKey();
}
static List<List<int>> IniteMap()
{
List<List<int>> map = new List<List<int>>();
for (int i = 0; i < 8; i++)
{
List<int> list = new List<int>();
for (int j = 0; j < 8; j++)
{
list.Add(0);
}
map.Add(list);
}
return map;
}
static void PrintMap(List<List<int>> map)
{
foreach (List<int> list in map)
{
foreach (int i in list)
{
Console.Write(i.ToString() + " ");
}
Console.WriteLine();
}
}
static bool IsOneLine(List<List<int>> map, int row, int colum)
{
int value = 1;
//横向
int i = 0;
for (i = 0; i < colum; i++)
if (map[row][i] == value)
return false;
//纵向
for (i = 0; i < row; i++)
if (map[i][colum] == value)
return false;
int a = row, b = colum;
while (a >= 0 && b >= 0)
{
if (map[a][b] == value)
return false;
else
{
a--;
b--;
}
}
a = row;
b = colum;
while(a>=0&&b<8)
{
if (map[a][b] == value)
return false;
else
{
a--;
b++;
}
}
return true;
}
public static int i = 0;
static void FindWay(List<List<int>> map, int row)
{
for (int i = row; i < map.Count; i++)
{
bool f = false;
int col = Getcol(i, map);
if (i == 0 && col == 5)
{
int c = 0;
}
for (int j = col; j < map[i].Count; j++)
{
if (IsOneLine(map, i, j))
{
map[i][j] = 1;
f = true;
break;
}
}
if (!f)
{
for (int j = 0; j < map[i].Count; j++)
{
map[i][j] = 0;
}
int a = i - 1;
if (a > -1)
FindWay(map, a);
}
}
PrintMap(map);
Console.WriteLine("*****************");
}
static int Getcol(int row, List<List<int>> map)
{
int col = 0;
for (int j = 0; j < map[row].Count; j++)
{
if (map[row][j] == 1)
{
col = j + 1;
map[row][j] = 0;
break;
}
}
return col;
}
}
}