Translate

Thursday, 7 April 2016

Sudoku Checker

package com.vikesh.gamesudoku;

public class SudokuChecker {

private static SudokuChecker instance;
private SudokuChecker(){}
public static SudokuChecker getInstance()
{
if(instance==null)
{
instance = new SudokuChecker();
}
return instance;
}
public boolean checkSudoku(int[][] sudoku)
{
return (checkHorizontal(sudoku)|| checkVertical(sudoku) || checkRegions(sudoku));
}

private boolean checkHorizontal(int[][] sudoku) {
for(int y=0;y<9;y++)
{
for(int xpos=0;xpos<9;xpos++)
{
if(sudoku[xpos][y]==0)
{
return false;
}
for(int x = xpos+1;x<9;x++)
{
if(sudoku[xpos][y]==sudoku[x][y] || sudoku[x][y]==0)
{
return false;
}
}
}
}
return true;
}
private boolean checkVertical(int [][] sudoku) {
for(int x=0;x<9;x++)
{
for(int ypos=0;ypos<9;ypos++)
{
if(sudoku[x][ypos]==0)
{
return false;
}
for(int y = ypos+1;y<9;y++)
{
if(sudoku[x][ypos]==sudoku[x][y] || sudoku[x][y]==0)
{
return false;
}
}
}
}
return true;
}

private boolean checkRegions(int[][] sudoku) {
for(int xRegion=0;xRegion<3;xRegion++)
{
for(int yRegion=0;yRegion<3;yRegion++)
{
if(!checkRegion(sudoku, xRegion, yRegion))
{
return false;
}
}
}
return true;
}
private boolean checkRegion(int[][] sudoku,int xRegion,int yRegion)
{
for(int xpos = xRegion*3;xpos<xRegion*3+3;xpos++)
{
for(int ypos = yRegion*3;ypos<yRegion*3+3;ypos++)
{
for(int x = xpos;x<xRegion*3+3;x++)
{
for(int y = ypos;y<yRegion*3+3;y++)
{
if((x!=xpos || y!=ypos) && (sudoku[xpos][ypos]==sudoku[x][y] || sudoku[x][y]==0))
{
return false;
}
}
}
}
}
return true;
}

}

No comments:

Post a Comment