Java helper code (having array instead of arraylist)


#1

I made a code with array instead of list for reference. Rest you guys can modify I’m sure.

static boolean check(char[][]a,int row,int col,char val,int n)
{
	// if the value is non zero then return false i mean ofc we dont wanna modify the pre existing values in the question
	if(a[row][col]!='.')return false;
	
	//check if val is present in current column
	for (int i = 0; i < n; i++) 
	{
		if(a[i][col]==val)return false;
	}
	//check if val is present in current row
	for(int i=0;i<n;i++)
	{
		if(a[row][i]==val)return false;
	}
	//check if val is present in current subgrid of 3*3
	int rs=(row/3)*3;
	int cs = (col/3)*3;
	
	for(int i=rs;i<=rs+2;i++)
	{
		for(int j=cs;j<=cs+2;j++)
		{
			if(a[i][j]==val)return false;
		}
	}

	return true;
}
static void solveSudoku(char[][]a)
{
	sudoku(a,1);
}
static boolean  sudoku(char[][]a,int x)
{
	int checkervar=0;
	int n=9;
	
	int i=0,j=0;
	//finding out where the 0 is located
	for( i=0;i<n;i++)
	{
		
		for(j=0 ;j<n;j++)
		{
			if(a[i][j]=='.') {
				checkervar=1;
				break;
			}
			
		}
		if(checkervar==1)break;
		
	}
	// i=row, j=column of 0
	if(checkervar==0)return true;
	//trying values from 1 to 9
	for(int k=1;k<=9;k++)
	{
		if(check(a, i, j, (char)(k+'0'), n))
		{
			a[i][j]=(char)(k+'0');
			
			if(sudoku(a,1))return true;
			//if the value doesnt work, then backtrack and erase the value then start again 
			a[i][j]='.';
		}
	}
	return false;
}