首页 > 代码库 > backtracing
backtracing
5月10日
1 37 Sudoku Slover
public void solveSudoku(char[][] board) { if(board == null || board.length == 0) return; slove(board); } public boolean slove(char[][] board){ for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { if (board[i][j] == ‘.‘) { for (char c = ‘1‘; c <= ‘9‘; c++) { if (isValue(board, i, j, c)) { board[i][j] = c; if (slove(board)) return true; else board[i][j] = ‘.‘; } } return false; } } } return true; } public boolean isValue(char[][] board, int row, int col, char c) { for (int i = 0; i < 9; i++) { if (board[i][col] != ‘.‘ && board[i][col] == c) return false; if (board[row][i] != ‘.‘ && board[row][i] == c) return false; if (board[3 * (row/3) + i/3][3 *(col/3) + i % 3] != ‘.‘ && board[3 * (row/3) + i/3][3 *(col/3) + i % 3] == c) return false; } return true; }
2 51 N-Queens
public List<List<String>> solveNQueens(int n) { List<List<String>> res = new ArrayList<>(); help(n, 0, new int[n], res); return res; } public void help(int n, int row, int[] colforrow, List<List<String>> res) { if (row == n) { ArrayList<String> item = new ArrayList<>(); for (int i = 0; i < n; i++) { StringBuilder sb = new StringBuilder(); for (int j = 0; j < n; j++) { if (colforrow[i] == j) sb.append(‘Q‘); else sb.append(‘.‘); } item.add(sb.toString()); } res.add(item); return; } for (int i = 0; i < n; i++) { colforrow[row] = i; if (check(row, colforrow)) { help(n, row + 1, colforrow, res); } } }
3 52 N-Queens II
public int totalNQueens(int n) { ArrayList<Integer> res = new ArrayList<>(); res.add(0); help(n, 0, new int[n], res); return res.get(0); } private void help(int n, int row, int[] columnForRow, ArrayList<Integer> res) { if(row==n) { res.set(0,res.get(0)+1); return; } for(int i=0;i<n;i++) { columnForRow[row]=i; if(check(row,columnForRow)) { help(n,row+1,columnForRow,res); } } } private boolean check(int row, int[] columnForRow) { for(int i=0;i<row;i++) { if(columnForRow[i]==columnForRow[row] || Math.abs(columnForRow[row]-columnForRow[i])==row-i) return false; } return true; }
4 77 combinations 分子问题
public List<List<Integer>> combine(int n, int k) { List<List<Integer>> res = new ArrayList<>(); if (n <= 0 || n < k) return res; help(n, k, 1, new ArrayList<Integer>(), res); return res; } public void help(int n, int k, int start, ArrayList<Integer> item, List<List<Integer>> res) { if (item.size() == k) { res.add(new ArrayList<Integer>(item)); return; } for (int i = start; i <= n; i++) { item.add(i); help(n, k, i + 1, item, res); item.remove(item.size() - 1); } }
backtracing
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。