Advertisement
Guest User

Untitled

a guest
Feb 27th, 2020
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.73 KB | None | 0 0
  1. package sudok;
  2.  
  3. import javax.swing.*;
  4.  
  5. public class Solver {
  6.  
  7. private int[][] m = new int [9][9];
  8. //private JTextField[][]jt = SudokuSwing.getJt();
  9.  
  10. public int getValue(int x,int y) {
  11. return m[x][y];
  12. }
  13.  
  14. public void setValue(int x,int y,int z) {
  15. //if(x<0||x>8||z<1||z>9||y<0||y>8){
  16. //throw new IllegalArgumentException("Aja Baja");
  17.  
  18. //}else
  19. m[x][y]=z;
  20. }
  21.  
  22. public void loadJt() {
  23. for (int i=0;i<9;i++) {
  24. for (int j=0;j<9;j++) {
  25. try {
  26. setValue(i,j,SudokuSwing.getJt(i,j));
  27. }
  28. catch(Exception e){
  29. //setValue(i,j,0);
  30. }
  31. }
  32. }
  33. }
  34.  
  35. public void clear(){
  36. for (int r=0;r<9;r++) {
  37. for (int c=0;c<9;c++) {
  38. m[r][c] = 0;
  39. }
  40. }
  41. }
  42.  
  43. /** Logic check, adds the specified number val only if it fulfills all the requirements */
  44. public boolean tryAddNbr(int row, int col, int val) {
  45. if(row<0||row>8||val<1||val>9||col<0||col>8){
  46. return false;
  47. }else{
  48. return !(isInCol(col, val))&&!(isInRow(row, val))&&!(isInMatrix(row, col, val))&&!(hasNum(row,col))&&!(numOutOfBounds(val));
  49. }
  50. }
  51.  
  52. public boolean isInCol(int col, int val){
  53. for( int i = 0; i<9; i++){
  54. if(getValue(i, col) == val){
  55. return true;
  56. }
  57. }
  58. return false;
  59. }
  60. public boolean isInRow(int row, int val){
  61. for(int i = 0; i<9; i++){
  62. if(getValue(row, i) == val){
  63. return true;
  64. }
  65.  
  66. }
  67. return false;
  68. }
  69.  
  70. public boolean hasNum(int row, int col){
  71. if(getValue(row, col)!=0){
  72. return true;
  73. }
  74. return false;
  75. }
  76. public boolean numOutOfBounds(int val){
  77. if( val > 9 || val < 1){
  78. return true;
  79. }
  80. return false;
  81. }
  82. public boolean isInMatrix(int row, int col, int val){
  83. int r = (row/3)*3;
  84. int c = (col/3)*3;
  85. for(int i =0; i<3; i++){
  86. for(int j = 0; j<3; j++){
  87. if(getValue(r+i, c+j) == val){
  88. return true;
  89. }
  90. }
  91. }
  92. return false;
  93. }
  94.  
  95. /** Wrapper method for solve */
  96. public boolean solve() {
  97. return solve(0, 0);
  98. }
  99. private boolean solve(int row, int col){
  100. if(col == 9){
  101. col=0;
  102. row++;
  103. }
  104.  
  105. if(row==9){
  106. return true;
  107. }
  108. for(int num = 1; num<10; num++){
  109. if(tryAddNbr(row,col,num)){
  110. setValue(row, col, num);
  111. if(solve(row, col+1)){
  112.  
  113. return true;
  114. }
  115. }else{
  116. setValue(row, col, 0);
  117. }
  118. }
  119. return false;
  120. }
  121.  
  122. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement