Posted By

pillow86 on 07/21/10


Tagged

game sudoku


Versions (?)

Sudoku


 / Published in: Java
 

  1. public class Sudoku {
  2.  
  3. static int[][] board;
  4.  
  5. public static void main(String[] arg) {
  6. String[] init = new String[9];
  7. init[0] = new String("060310050");
  8. init[1] = new String("000406000");
  9. init[2] = new String("003000700");
  10. init[3] = new String("030805090");
  11. init[4] = new String("102090304");
  12. init[5] = new String("070103060");
  13. init[6] = new String("006000900");
  14. init[7] = new String("000502000");
  15. init[8] = new String("040080020");
  16.  
  17. board = new int[9][9];
  18. for (int i=0;i<9;i++) {
  19. for (int j=0;j<9;j++) {
  20. board[i][j] = Integer.parseInt(init[i].substring(j, j+1));
  21. }
  22. }
  23. printBoard();
  24. solveNext(-1,-1);
  25.  
  26. // System.out.println("i="+i+", j="+j);
  27. }
  28.  
  29. private static boolean solveNext(int i, int j) {
  30. boolean result = false;
  31. j = (j+1)%9;
  32. i = i+(j==0?1:0);
  33. if (i==9) {
  34. result = true;
  35. printBoard();
  36. } else {
  37. if (board[i][j] != 0) {
  38. result = solveNext(i,j);
  39. } else {
  40. for (int val = 1; val <= 9 && !result; ++val) {
  41. if (cellValid(i,j, val)) {
  42. board[i][j] = val;
  43. result = solveNext(i,j);
  44. }
  45. }
  46. board[i][j] = 0;
  47. }
  48. }
  49. return result;
  50. }
  51.  
  52. private static boolean cellValid(int i, int j, int val) {
  53. for (int r=0;r<9;r++)
  54. for (int c=0;c<9;c++)
  55. if ((r!=i||c!=j)&&
  56. board[r][c]!=0&&
  57. board[r][c]==val&&
  58. (r==i||c==j||(i/3==r/3&&j/3==c/3))) {
  59. return false;
  60. }
  61. return true;
  62. }
  63.  
  64. public static void printBoard() {
  65. for (int i=0;i<9;i++) {
  66. for (int j=0;j<9;j++) {
  67. System.out.print(board[i][j]);
  68. }
  69. System.out.println();
  70. }
  71. System.out.println("---------");
  72. }
  73. }

Report this snippet  

You need to login to post a comment.