首页 > 代码库 > Sudoku
Sudoku
Inefficient Print All
public static void main(String[] args) { solveSudoku(new char[N][N]); } static int N =9; //4 static int s = 3; //2 static boolean solved = false; public static void solveSudoku(char[][] board){ solveSudoku(board, 0, 0); } private static void solveSudoku(char[][] board, int rowFrom, int colFrom) { for(int r = rowFrom; r<N; ++r) { for(int c = colFrom; c<N; ++c) { int n = 1; while(board[r][c]==‘\0‘ && n<=N) { if(isValid(board, r, c, Character.forDigit(n, 10))) { board[r][c] = Character.forDigit(n, 10); solveSudoku(board, r, c+1); if(solved) //comment this out to get all sudoku return; board[r][c] = ‘\0‘; } ++n; } if(n == N+1) return; } colFrom = 0; } solved = true; for(int i = 0; i< N; i++) { for(int j = 0; j< N; j++) System.out.print(board[i][j] + ","); System.out.println(); } System.out.println("=============="); } private static boolean isValid(char[][] board, int row, int col, char val) { for(int c = 0; c<N; ++c) if(board[row][c] == val) return false; for(int r = 0; r<N; ++r) if(board[r][col] == val) return false; int rr = row/s; int cc = col/s; for(int r = rr*s; r<rr*s+s; ++r) for(int c = cc*s; c<cc*s+s; ++c) if(board[r][c] == val) return false; return true; }
Sudoku
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。