标签:[] private list int div board col val blog
class Solution { public List<List<String>> solveNQueens(int n) { int[][] board=new int[n][n]; List<List<String>> res=new ArrayList<List<String>>(); nQueens(0,board,res); return res; } private void nQueens(int i, int[][] board, List<List<String>> res){ if(i==board.length) { List<String> list=new ArrayList<String>(); for(int y=0;y<board.length;y++) { String row=""; for(int x=0;x<board.length;x++) row+=board[y][x]==1?‘Q‘:‘.‘; list.add(row); } res.add(list); return; } for(int j=0;j<board.length;j++) if(board[i][j]==0) { board[i][j]=1; fillQueuePath(i, j, board, -1); nQueens(i+1,board,res); fillQueuePath(i, j, board, 1); board[i][j]=0; } } private void fillQueuePath(int i, int j, int[][] board, int val){ for(int k=1;i+k<board.length;k++) { board[i+k][j]+=val; if(j-k>=0) board[i+k][j-k]+=val; if(j+k<board.length) board[i+k][j+k]+=val; } } }
标签:[] private list int div board col val blog
原文地址:http://www.cnblogs.com/asuran/p/7591343.html