Am searching for an efficient algorithm for generating solved Sudoku given the size(rows and column) of the board as input.

i have written a program but its performing badly when the number of rows and column exceeds 40 (ie 40 x 40 matrix ).

import java.util.Scanner;

public class Main {
	public static int [][]board;
	public static int n=0;
	public static int m=0;

	public static boolean isValid(int row,int matrix,int value){
// Checks vertically
		for(int i=0;i<n;i++){
				return false;
			else if(board[i][0]==0){
//No need to check horizontally 

//checks  the m x m blocks
		for(int i=matrix;i<matrix+m;i++){
			for(int j=0;j<m;j++)
					return false;
				else if(board[i][j]==0){
		return true;
	private static void fillData(int row, int j) {		
		for(int i=0;i<n;i++){			
	public static void main(String[] args) {
		Scanner sc=new Scanner(;		
		int matrix=0;
		int count=0;
		n=(int) Math.pow(m, 2);
		board=new int[n][n];				
		for(int i=0;i<n;i++){
/* For a 9x9 board , matrix values will be 0,3,6  which are the row index of the 3x3 boxes */

			for(int j=1;j<=n;j++){
		for (int k = 0; k < n; k++) {
			for(int j=0;j<n;j++)
				System.out.print(board[k][j]+" ");

Let me know if there are any optimizations that i can make or any algorithm that performs well

Well, just for the hell of it, I'm going to write a Sudoku program also. It might take me a few days since I have other things to do this week and I don't know how to play the game yet. Lol. Could you post your input that's taking a long time to run? Also, I'm not sure I understand how you're getting input to begin with. Unless you redirected stdin to a file, it looks like its from the keyboard.

edit: Also, you realize you can probably find hundreds of Suduko programs written in Java online, right?

second edit: After some initial reading, this looks like it is going to be harder than I thought... you're definitely better off getting help by searching the web for some better algorithms than waiting on me. And I don't understand how your code works either... does it work correctly (on smaller puzzles)?

edit (yet again :) ):
Are you using a brute force algorithm to solve this? Such as

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.