Created
March 10, 2012 20:15
-
-
Save AsadR/2012938 to your computer and use it in GitHub Desktop.
Dumb Eight Queen Solution in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Board.java | |
* | |
* Part of the Eight Queen puzzle solver by Asad ur Rehman <asad.rehman@gmail.com> | |
* | |
*/ | |
public class Board { | |
private int n; | |
private byte[][] values; | |
private int num_queens; | |
public Board(int dim) { | |
n = dim; | |
values = new byte[n][n]; // automatically initialized to 0x0 | |
num_queens = 0; | |
} | |
public Board(Board b) { | |
n = b.n(); | |
values = new byte[n][n]; | |
for(int i = 0; i < n; i++) | |
for(int j = 0; j < n; j++) | |
values[i][j] = b.values[i][j]; | |
num_queens = b.num_queens(); | |
} | |
public void markQueen(int r, int c) { | |
for(int i = 0; i < n; i++) { | |
for(int j = 0; j < n; j++) { | |
if(i == r && j == c) | |
values[i][j] = 'Q'; | |
else if( (i == r) || (j == c) || (r-c) == (i-j) || (r+c) == (i+j) ) | |
values[i][j] = 'X'; | |
} | |
} | |
num_queens++; | |
} | |
public String asString() { | |
StringBuilder sb = new StringBuilder(); | |
for(int i = 0; i < n(); i++) | |
for(int j = 0; j < n(); j++) | |
sb.append(values[i][j]); | |
return sb.toString(); | |
} | |
public boolean isEmptyAt(int r, int c) { | |
return (values[r][c] == 0x0); | |
} | |
public int n() { | |
return n; | |
} | |
public byte[][] values() { | |
return values; | |
} | |
public int num_queens() { | |
return num_queens; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Solution.java | |
* | |
* 8-Queen puzzle solver by Asad ur Rehman <asad.rehman@gmail.com> | |
* | |
* Sun Mar 11 01:14:39 PKT 2012 | |
* | |
* real 0m1.644s | |
* user 0m2.385s | |
* sys 0m0.126s | |
* | |
*/ | |
import java.util.HashSet; | |
public class Solution { | |
private HashSet<String> cache; | |
public static void main(String[] args) { | |
Solution s = new Solution(); | |
Board b = new Board(8); | |
s.solve(b); | |
} | |
public Solution() { | |
cache = new HashSet<String>(); | |
} | |
void solve(Board b) { | |
if(cache.contains(b.asString())) | |
return; | |
else | |
cache.add(b.asString()); | |
if(b.n() == b.num_queens()) { | |
System.out.println("Found " + b.num_queens() + " queens solution"); | |
return; | |
} | |
for(int i = 0; i < b.n(); i++) { | |
for(int j = 0; j < b.n(); j++) { | |
if(b.isEmptyAt(i,j)) { | |
Board tmp = new Board(b); | |
tmp.markQueen(i,j); | |
solve(tmp); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment