All pastes #966479 Raw Edit

Miscellany

public text v1 · immutable
·published 2008-04-01 19:36 UTC
rendered paste body
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
 
public class Sudoku{
 
	//***************Definierar variabler************************
     
        public int[][] matrix;
        public boolean[][] change;
       
        public int finalCol=8;
        public int finalRow = 8;

        public Sudoku(){
        	 
            //Create matrix
            matrix = new int[9][9];
            change = new boolean[9][9];

    }
    


      //********Den rekursiva metoden för att lösa sodukot*******
        public boolean solveNext(int row, int col) {
            
            if(col == 9){
                row++;
                col = 0;
            }

            if(change[row][col]== false ){
            	return solveNext(row,col+1);
            }

            for(int k=1; k<=9;k++){				//testa tal 1-9 i varje ruta tills en som passar har hittas
                    
                    matrix[row][col] = k;

                    if(chk(matrix,row,col)){
                            if(row==finalRow && col==finalCol){
                                    return true;
                            }
                            
                            if(solveNext(row,col+1)==true){			//Om matrisen uppfyller reglerna så ta ett steg fram
                                    return true;
                            }
                    }
            }
            
            matrix[row][col] = -1;

            return false;
    }

      //**Metod för att kontrollera om matrisen uppyller reglerna***
        public boolean chk(int[][] matrix, int row, int col){
        	 
        	//**********Kontrollerar så den insatta siffran inte är en dublett***********
        	for(int i = 0; i<=8;i++){
        		if (matrix[row][i] == matrix[row][col] && i!=col && matrix[row][i]!=-1){
        			return false;
        		}
        	}
        	
        	for(int i = 0; i<=8;i++){
        		if (matrix[i][col] == matrix[row][col] && i!=row && matrix[i][col]!=-1){
        			return false;
        		}
        	}
        	

 
             //******Metod för att kontollera om det finns dubletter i den specifika underkvadraten****
        		int tempRow=row;
        		int tempCol=col;
        		
        		while(row % 3!=0){
        			row--;
        		}
        		while(col % 3 != 0){
        			col--;
        		}
      		for(int i = row; i<=row+2;i++){
        			for(int j=col; j<=col+2; j++)
        				if (matrix[tempRow][tempCol]==matrix[i][j] && matrix[i][j]!=-1 && (tempRow!= i && tempCol !=j)){
                            return false;
                    }       
        		}
        		

 
                return true;
 
        }
        
        public int[][] getMatrix(){
        	return matrix;
        }

        public boolean[][] getChange(){
        	return change;
        }



 
}