Algorithm that will check whether the given grid of numbers represents a valid Sudoku puzzle In PHP
Sudoku is a number-placement puzzle. The objective is to fill a
9 × 9
grid with numbers in such a way that each column, each row, and each of the nine 3 × 3
sub-grids that compose the grid all contain all of the numbers from 1
to 9
one time.
Implement an algorithm that will check whether the given
grid
of numbers represents a valid Sudoku puzzle according to the layout rules described above. Note that the puzzle represented by grid
does not have to be solvable.
<?php function sudoku2($grid) {
$n=count($grid);
$m=count($grid[0]);
if($n==$m)
{
$status=true;
foreach($grid as $key=>$gridDetail)
{
$gridDetail=str_replace (".","",$gridDetail);
$gridDetail=array_filter($gridDetail);
foreach($gridDetail as $keydetail=>$gridInfo)
{
$arrayindex=checkdetail($key,$keydetail);
if(isset($sqarearray[$arrayindex]))
{
if(in_array($gridInfo,$sqarearray[$arrayindex]))
{
$status=false;
return $status;
//print_r($sqarearray[$arrayindex]);
}else
{
$sqarearray[$arrayindex][]=$gridInfo;
// print_r($sqarearray[$arrayindex]);
}
}else
{
$sqarearray[$arrayindex][]=$gridInfo;
// print_r($sqarearray[$arrayindex]);
}
if(isset($horizontal[$keydetail])){
if(in_array($gridInfo,$horizontal[$keydetail]))
{
$status=false;
return $status;
}else{
$horizontal[$keydetail][]=$gridInfo;
}
}else
{
$horizontal[$keydetail][]=$gridInfo;
}
}
$array= array_diff_assoc ($gridDetail,array_unique($gridDetail));
if(count($array) >= 1)
{
$status=false;
return $status;
// $countarray[]=count($array);
}
}
return $status;
}else
{
return false;
}
}
function checkdetail($var,$hor)
{
if(($var<3) && ($hor<3))
{
return 0;
}elseif(($var>=3 && $var<6)&& ($hor<3))
{
return 1;
}elseif(($var>=6 && $var<9) && ($hor<3))
{
return 2;
}elseif(($hor>=3 && $hor<6) && ($var<3))
{
return 3;
}
elseif(($hor>=6 && $hor<9) && ($var<3))
{
return 4;
}elseif(($hor>=3 && $hor<6) && ($var>=3 && $var<6))
{
return 5;
}
elseif(($hor>=6 && $hor<9) && ($var>=3 && $var<6))
{
return 6;
}
elseif(($hor>=6 && $hor<9) && ($var>=6 && $var<9))
{
return 7;
}
elseif(($hor>=3 && $hor<6) && ($var>=6 && $var<9))
{
return 8;
}
}
$grid=array(array(".",".",".",".",".",".","5",".","."),
array(".",".",".",".",".",".",".",".","."),
array(".",".",".",".",".",".",".",".","."),
array("9","3",".",".","2",".","4",".","."),
array(".",".","7",".",".",".","3",".","."),
array(".",".",".",".",".",".",".",".","."),
array(".",".",".","3","4",".",".",".","."),
array(".",".",".",".",".","3",".",".","."),
array(".",".",".",".",".","5","2",".","."));
$sudokuinfo=sudoku2($grid);
print_r($sudokuinfo);
Comments
Post a Comment