А что тут думать-то? тут писать надо  Держи (правда на C#, но у тебя же есть опыт перевода C#->Java ;-) ):
| Код | /* * Задача: * Расставить на шахматной доске NхN M ферзей, чтобы они: * 1) не били друг друга * 2) держали все клетки под боем * * перебор организовать рекурсивно */
using System; using System.Collections.Generic; using System.Text;
namespace Merhaba_FiveQueen { public class myPoint { public int x, y; public myPoint(int x, int y) { this.x = x; this.y = y; } } class Program { const int N = 8; //размерность доски const int M = 5; //количество ферзей static bool[] d1 = new bool[2*N]; //главная диагональ static bool[] d2 = new bool[2*N]; static bool[] g = new bool[N]; static bool[] v = new bool[N]; static Stack<myPoint> s = new Stack<myPoint>(); static int count = 0;
//return true если все клетки под боем static bool allFill() { bool res = true; bool [,] f = new bool[N,N]; for (int i = 0; i < N; i++) { if (!g[i]) for (int j = 0; j < N; j++) f[i, j] = true; if (!v[i]) for (int j = 0; j < N; j++) f[j, i] = true; } //d1 for (int i = 0; i < N; i++) { int x = i, y = 0; if (!d1[N-i]) for (int j = 0; j < N-i; j++) f[x++, y++] = true; x = 0; y = i; if (!d1[N+i]) for (int j = 0; j < N - i; j++) f[x++, y++] = true; } //d2 for (int i = 0; i < N; i++) { int x = 0, y = N-1-i; if (!d2[y]) for (int j = 0; j <= N-1 - i; j++) f[x++, y--] = true; x = i; y = N-1; if (!d2[i+N-1]) for (int j = 0; j <= N-1 - i; j++) f[x++, y--] = true; } for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) res &= f[i, j]; return res; }
//вывод ответа в шахматной нотации static void output() { myPoint[] tmp = new myPoint[s.Count]; s.CopyTo(tmp, 0); Console.Write("{0} ", count); for (int i = s.Count - 1; i >= 0 ; i--) Console.Write("{0} {1} ", (char)(N-1 - i + 97), tmp[i].y+1); Console.WriteLine(); }
//основная процедура поиска static void search(int x, int y, int level) { if (level == M) { if (allFill()) { count++; output(); } } else if (x < N) { while (x < N) { if (g[x] && v[y] && d1[N - x + y] && d2[x + y]) { s.Push(new myPoint(x, y)); g[x] = false; v[y] = false; d1[N - x + y] = false; d2[x + y] = false; search(x + 1, 0, level + 1); s.Pop(); g[x] = true; v[y] = true; d1[N - x + y] = true; d2[x + y] = true; } x += (++y / N); y %= N; } } }
static void Main(string[] args) { Console.SetOut(new System.IO.StreamWriter("output.txt")); int x = 0, y = 0; for (int i = 0; i < N; i++) { v[i] = true; g[i] = true; } for (int i = 0; i < 2*N; i++) { d1[i] = true; d2[i] = true; } search(0, 0, 0); Console.Out.Close(); } } }
|
Количество вариантов - 728, что, кстати, совпадает с http://sources.codenet.ru/download/3886/5_%D4%E5%F0%E7%E5%E9%20%EF%E5%F0%E5%E1%EE%F0.html программами. |