public bool AddQueen(QueenItem queenItem) { MarkRowVisited(queenItem.Row); MarkColVisited(queenItem.Col); MarkDiagonalLeftUpVisited(queenItem.Row, queenItem.Col); MarkDiagonalRightUpVisited(queenItem.Row, queenItem.Col); MarkDiagonalLeftDownVisited(queenItem.Row, queenItem.Col); MarkDiagonalRightDownVisited(queenItem.Row, queenItem.Col); QueenList.Add(queenItem); return(true); }
public static int GetNQueens(int n) { var result = new List <List <QueenItem> >(); int min = Int32.MinValue; for (int i = 0; i < n; i++) { var current = new QueenItem(i, 0, n - 1, n - 1); current.AddQueen(current); Queue <QueenItem> queue = new Queue <QueenItem>(); queue.Enqueue(current); while (queue.Count > 0) { var currentItem = queue.Dequeue(); if (currentItem.Size == min) { result.Add(currentItem.QueenList); } if (currentItem.Size > min) { result = new List <List <QueenItem> > { currentItem.QueenList }; min = currentItem.Size; } if (currentItem.Col + 1 < n) { for (int j = 0; j < n; j++) { if (currentItem.IsSafe(j, currentItem.Col + 1)) { var newItem = new QueenItem(j, currentItem.Col + 1, n - 1, n - 1); currentItem.QueenList.ForEach(item => newItem.AddQueen(item)); newItem.AddQueen(newItem); queue.Enqueue(newItem); } } } } } return(min == n ? result.Count : 0); }