You are viewing a single comment's thread. Return to all comments →
can anyone tell where is the error in this code
class Solution { public boolean isSafe(int row, int col, char[][] board) { //horizontal for(int j=0; j
//vertical for(int i=0; i<board.length; i++) { if(board[i][col] == 'Q') { return false; } } //upper left int r = row; for(int c=col; c>=0 && r>=0; c--, r--) { if(board[r][c] == 'Q') { return false; } } //upper right r = row; for(int c=col; c<board.length && r>=0; r--, c++) { if(board[r][c] == 'Q') { return false; } } //lower left r = row; for(int c=col; c>=0 && r<board.length; r++, c--) { if(board[r][c] == 'Q') { return false; } } //lower right for(int c=col; c<board.length && r<board.length; c++, r++) { if(board[r][c] == 'Q') { return false; } } return true;
}
public void saveBoard(char[][] board, List> allBoards) { String row = ""; List newBoard = new ArrayList<>();
for(int i=0; i<board.length; i++) { row = ""; for(int j=0; j<board[0].length; j++) { if(board[i][j] == 'Q') row += 'Q'; else row += '.'; } newBoard.add(row); } allBoards.add(newBoard);
public void helper(char[][] board, List> allBoards, int col) { if(col == board.length) { saveBoard(board, allBoards); return; }
for(int row=0; row<board.length; row++) { if(isSafe(row, col, board)) { board[row][col] = 'Q'; helper(board, allBoards, col+1); board[row][col] = '.'; } }
public List> solveNQueens(int n) { List> allBoards = new ArrayList<>(); char[][] board = new char[n][n];
helper(board, allBoards, 0); return allBoards;
} }
Seems like cookies are disabled on this browser, please enable them to open this website
KnightL on a Chessboard
You are viewing a single comment's thread. Return to all comments →
can anyone tell where is the error in this code
class Solution { public boolean isSafe(int row, int col, char[][] board) { //horizontal for(int j=0; j
}
public void saveBoard(char[][] board, List> allBoards) { String row = ""; List newBoard = new ArrayList<>();
}
public void helper(char[][] board, List> allBoards, int col) { if(col == board.length) { saveBoard(board, allBoards); return; }
}
public List> solveNQueens(int n) { List> allBoards = new ArrayList<>(); char[][] board = new char[n][n];
} }