Monday, September 8, 2014

Place 8 queens on chess board in such a way that other queens are not in same row, column and diagonally in Java


//
// Comment

 public static final int chessGridSize = 8;

 public static void placeQueens(List list, Integer[] columns,
   int row) {
  if (row == chessGridSize ) {
   list.add(columns.clone());
  } else {
   for (int col = 0; col < chessGridSize; col++) {
    if (canPlaceQueen(columns, row, col)) {
     columns[row] = col;
     placeQueens(list, columns, row + 1);
    }

   }
  }
 }

 private static boolean canPlaceQueen(Integer[] columns, int row1, int col1) {

  for (int row2 = 0; row2 < row1; row2++) {
   int col2 = columns[row2];

   if (col1 == col2)
    return false;

   if (Math.abs(col2 - col1) == Math.abs(row2 - row1))
    return false;
  }
  return true;
 }


No comments:

Post a Comment