Skip to content

Commit

Permalink
Added documentation to queens.dart
Browse files Browse the repository at this point in the history
Documented all methods and steps taken during the algorithms.
  • Loading branch information
martin-headspace committed Feb 18, 2020
1 parent ee9f2ae commit 4d6f95e
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 30 deletions.
56 changes: 31 additions & 25 deletions .idea/workspace.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

30 changes: 25 additions & 5 deletions eight_queens/lib/queens.dart
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
/**
* Queen Resolver class
* Solved using algorithm found in: https://www.geeksforgeeks.org/n-queen-problem-using-branch-and-bound/
*/
///
///Queen Resolver class
///Solved using algorithm found in: https://www.geeksforgeeks.org/n-queen-problem-backtracking-3/
///Adapted for use with Dart and Flutter
///
import 'package:shared_preferences/shared_preferences.dart';

class QueenResolver {

int count = 0;

///
/// Checks if a queen can be placed on a [board] in a [row] and [col]
/// Returns a [bool] if it's safe to place it [true] or not [false]
///
Future<bool> isSafe(board, int row, int col, int n) async {
// Check row on the left side
for (var i = 0; i < col; i++) {
Expand Down Expand Up @@ -40,8 +45,15 @@ class QueenResolver {
return true;
}

///
/// Main eight queens algorithm
/// Receives a single [board] and [col] positions, as well as [n] queens.
/// Will return [true] when solved.
///
Future<bool> solveQueens(board, int col, int n) async {

/* Solve for the base case : All queens are placed
* Then, store it into local storage */
if (col >= n) {
count++;
storeSolution(board).then((value) {
Expand All @@ -50,6 +62,7 @@ class QueenResolver {
}

var res = false;
/** Consider the [col] and try placing it on the [board] **/
for(int i = 0; i < n; i++) {
if(await isSafe(board, i, col, n)){
board[i][col] = 1;
Expand All @@ -59,7 +72,10 @@ class QueenResolver {
}
return res;
}


/// Stores a complete [board] into [SharedPreferences]
/// Because the [board] is not completely initialized, it requires to convert all [null] values to [0].
/// Stores also the current [count] into [SharedPreferences]
Future storeSolution(List<List<int>> board) async {
for(int i = 0; i < board.length; i++) {
for(int x = 0; x < board[i].length ; x++) {
Expand All @@ -73,6 +89,10 @@ class QueenResolver {
await prefs.setInt('count', count);
}

///
/// Function entryway to solve for [n] queens.
/// Will return [count] for the app's purposes
///
Future<int> solve(int n) async {
// Create the initial queens board
List<List<int>> board = new List.generate(n, (_) => new List(n));
Expand Down

0 comments on commit 4d6f95e

Please sign in to comment.