Created
August 17, 2014 21:18
-
-
Save chrislukkk/1a06f5d153c8b2cf3d7e to your computer and use it in GitHub Desktop.
Career cup 9.9
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
package Chapter9; | |
import java.util.ArrayList; | |
public class EightQueen { | |
public static final int CHESS_BOARD_LENGTH = 8; | |
public static int count = 0; | |
//Check if the position is valid based on previous assignment of other queens | |
private static boolean isValid(int row, int col, ArrayList<Integer> prevRows) { | |
for(int i = 0; i < col; i++) { | |
if(row == prevRows.get(i) || Math.abs(row - prevRows.get(i)) == col - i) | |
return false; | |
} | |
return true; | |
} | |
public static void printAll() { | |
count = 0; | |
printAllWays(0, new ArrayList<Integer>()); | |
} | |
private static void printAllWays(int curCol, ArrayList<Integer> prevRows) { | |
for(int row = 0; row < CHESS_BOARD_LENGTH; row++) { | |
if(!isValid(row, curCol, prevRows)) | |
continue; | |
int nextCol = curCol + 1; | |
ArrayList<Integer> nextRows = new ArrayList<Integer>(); | |
nextRows.addAll(prevRows); | |
nextRows.add(row); | |
if(nextCol == CHESS_BOARD_LENGTH) | |
printBoard(nextRows); | |
else { | |
printAllWays(nextCol, nextRows); | |
} | |
} | |
} | |
//print the chess board for testing | |
private static void printBoard(ArrayList<Integer> nextRows) { | |
System.out.println("Chess Board " + (count++) + ": "); | |
for(int row = 0; row < CHESS_BOARD_LENGTH; row++) { | |
for(int col = 0; col < CHESS_BOARD_LENGTH; col++) { | |
if(nextRows.get(col) == row) | |
System.out.print(". "); | |
else | |
System.out.print("X "); | |
} | |
System.out.println(); | |
} | |
System.out.println(); | |
} | |
public static void main(String[] args) { | |
EightQueen.printAll(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment