privatebooleanthreaten(introw,intcolumn){introwT=row;intcolumnT=column;// same row checkfor(inti=0;i<boardSize;i++){if(board[row][i])returntrue;}// up left diagonal checkwhile(rowT>=0&&columnT>=0){if(board[rowT][columnT])returntrue;rowT--;columnT--;}rowT=row;columnT=column;// up right diagonal checkwhile(rowT>=0&&columnT<boardSize){if(board[rowT][columnT])returntrue;rowT--;columnT++;}rowT=row;columnT=column;// down left diagonal checkwhile(rowT<boardSize&&columnT>=0){if(board[rowT][columnT])returntrue;rowT++;columnT--;}rowT=row;columnT=column;// down right diagonal checkwhile(rowT<boardSize&&columnT<boardSize){if(board[rowT][columnT])returntrue;rowT++;columnT++;}returnfalse;}
/** * Created by liqiushi on 3/20/14. */publicclassBacktracking{intboardSize;boolean[][]board;intk=1;publicBacktracking(intboardSize){this.boardSize=boardSize;board=newboolean[boardSize][boardSize];}publicstaticvoidmain(String[]args){Backtrackingbacktracking=newBacktracking(8);backtracking.init();backtracking.placeQueen_oneSolution(0);backtracking.init();backtracking.placeQueen_allSolutions(0);}privatevoidprintBoard(){for(inti=0;i<boardSize;i++){for(intj=0;j<boardSize;j++){if(board[i][j]){System.out.print("Q ");}else{System.out.print(". ");}}System.out.println();}System.out.println(k++);}privatebooleanplaceQueen_oneSolution(intcolumn){introw=0;booleansuccess=false;while(row<boardSize){if(column==boardSize){printBoard();returntrue;}if(threaten(row,column)){row++;}else{board[row][column]=true;success=placeQueen_oneSolution(column+1);if(!success){board[row][column]=false;row++;}}}returnsuccess;}privatevoidplaceQueen_allSolutions(intcolumn){introw=0;while(row<boardSize){if(column==boardSize){printBoard();return;}if(threaten(row,column)){row++;}else{board[row][column]=true;placeQueen_allSolutions(column+1);board[row][column]=false;row++;}}}privatebooleanthreaten(introw,intcolumn){introwT=row;intcolumnT=column;// same row checkfor(inti=0;i<boardSize;i++){if(board[row][i])returntrue;}// up left diagonal checkwhile(rowT>=0&&columnT>=0){if(board[rowT][columnT])returntrue;rowT--;columnT--;}rowT=row;columnT=column;// up right diagonal checkwhile(rowT>=0&&columnT<boardSize){if(board[rowT][columnT])returntrue;rowT--;columnT++;}rowT=row;columnT=column;// down left diagonal checkwhile(rowT<boardSize&&columnT>=0){if(board[rowT][columnT])returntrue;rowT++;columnT--;}rowT=row;columnT=column;// down right diagonal checkwhile(rowT<boardSize&&columnT<boardSize){if(board[rowT][columnT])returntrue;rowT++;columnT++;}returnfalse;}privatevoidinit(){for(inti=0;i<boardSize;i++){for(intj=0;j<boardSize;j++)board[i][j]=false;}}}