Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package queens;
- import java.util.Scanner;
- public class Queens {
- static int[] queens;
- int row = 0;
- public Queens() {
- Scanner scan = new Scanner(System.in);
- System.out.println("Please Enter A Number");
- //int x = scan.nextInt();
- queens = new int[4];
- }
- boolean safe(int col) {
- int current = queens[col];
- for (int i = 1; i <= row; i++) {
- int pre = queens[col - i];
- if (pre == current
- || pre == current - i
- || pre == current + i) {
- return false;
- }
- }
- return true;
- }
- public void placeQueens(int row) {
- for (int col = 0; col < queens.length; col++) {
- if (safe(col)) {
- queens[row] = col;
- if (row == queens.length - 1) {
- printOut();
- } else {
- row++;
- placeQueens(row);
- }
- }
- }
- }
- public void printOut() {
- for (int i = 0; i < queens.length; i++) {
- for (int j = 0; j < queens.length; j++) {
- if (queens[i] == j) {
- System.out.print("Q");
- } else {
- System.out.print("*");
- }
- }
- System.out.println("");
- }
- System.out.println("");
- }
- public static void main(String[] args) {
- Queens q = new Queens();
- q.placeQueens(0);
- //q.printOut();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement