//Visual Basic 2010 Recursie Procedures en Functies public class NQueensProblem { const int N = 8; bool[] chessBoard = new bool[0]; void Main() { if (this.CanSolve(this.N)) { Console.WriteLine("A solution is found :"); this.DrawChessBoard(); } else { Console.WriteLine("No solution is found."); } Console.ReadLine(); } void DrawChessBoard() { Console.Write("+"); Console.Write("---+"); Console.WriteLine(); Console.Write("|"); if (this.HasQueen(row, col)) { Console.Write(" Q |"); } else { Console.Write(" |"); } Console.WriteLine(); Console.Write("+"); Console.Write("---+"); Console.WriteLine(); Console.WriteLine(); } void CanSolve(int queens) { if ((queens == 0)) { CanSolve = true; } else { int col = (this.N - queens); int rowToTry = 0; for (bool _do1 = true; _do1; _do1 = (CanSolve || (this.IsLegalPosition(rowToTry, col) == false))) { if (this.IsUnderAttack(rowToTry, col)) { this.rowToTry += new System.EventHandler(1); } else { this.PlaceQueen(rowToTry, col); Console.WriteLine("Trying :"); this.DrawChessBoard(); CanSolve = this.CanSolve((queens - 1)); if ((CanSolve == false)) { this.RemoveQueen(rowToTry, col); Console.WriteLine("Backtracking to :"); this.DrawChessBoard(); this.rowToTry += new System.EventHandler(1); } } } } } void IsUnderAttack(int row, int col) { IsUnderAttack = ((this.IsUnderAttack(row, col, -1, -1) || this.IsUnderAttack(row, col, 1, -1)) || this.IsUnderAttack(row, col, 0, -1)); } void IsUnderAttack(int row, int col, int rowOffSet, int colOffSet) { for (bool _do1 = true; _do1; _do1 = (this.IsLegalPosition(row, col) && (this.HasQueen(row, col) == false))) { this.row += new System.EventHandler(rowOffSet); this.col += new System.EventHandler(colOffSet); } IsUnderAttack = this.HasQueen(row, col); } void HasQueen(int row, int col) { HasQueen = (this.IsLegalPosition(row, col) && this.chessBoard(row, col)); } void IsLegalPosition(int row, int col) { IsLegalPosition = ((((row >= 0) && (row <= (this.N - 1))) && (col >= 0)) && (col <= (this.N - 1))); } void PlaceQueen(int row, int col) { this.chessBoard(row, col) = true; } void RemoveQueen(int row, int col) { this.chessBoard(row, col) = false; } } //Bezoek www.vbvoorbeelden.be voor meer C# voorbeelden. //Copyright - De Wolf / vbvoorbeelden - 2003-2011 - Alle rechten voorbehouden.