Created
September 23, 2014 16:32
-
-
Save bitcpf/ae50050120459bf50228 to your computer and use it in GitHub Desktop.
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
import java.util.ArrayList; | |
public class Q9_9 { | |
// static int cnt = 0; | |
static int GRID_SIZE = 8; | |
public static void placeQueens(int row, Integer[] columns, ArrayList<Integer[]> results){ | |
if (row == GRID_SIZE){ | |
for(int i = 0; i < columns.length;i++){ | |
System.out.print(columns[i]); | |
} | |
// cnt ++; | |
System.out.println(); | |
// System.out.println(cnt); | |
results.add(columns.clone()); | |
}else | |
{ | |
for(int col = 0; col < GRID_SIZE; col ++){ | |
if(checkValid(columns,row,col)){ | |
columns[row] = col; | |
placeQueens(row + 1,columns,results); | |
} | |
} | |
} | |
} | |
private static boolean checkValid(Integer[] columns, int row1, int col1) { | |
// TODO Auto-generated method stub | |
for(int row2 = 0; row2 < row1; row2 ++){ | |
int col2 = columns[row2]; | |
if(col1 == col2) return false; | |
int columnDistance = Math.abs(col2 - col1); | |
int rowDistance = row1 - row2; | |
if(columnDistance == rowDistance) return false; | |
} | |
return true; | |
} | |
public static void main(String[] args){ | |
Integer[] columns = new Integer[GRID_SIZE]; | |
ArrayList<Integer[]> rst = new ArrayList<Integer[]>(); | |
placeQueens(0, columns, rst); | |
System.out.println(rst.size()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment