Thursday, December 18, 2014

N Queen problem in java


	public static boolean placeQueens(int[][] board, int row, int n)
	{
		if(row >= n) return true;
		
		for(int c = 0; c < n; c++)
		{
			if(isValidPlace(board, row, c, n))
			{
                                 /* Place this queen in board[i][col] */
				board[row][c] = 1;
				
                                // recur for each row
				if(placeQueens(board, row+1, n))
					return true;

				 /* If placing queen in board[i][col] doesn't lead to a solution
                                    then remove queen from board[i][col] */
				board[row][c] = 0; //Backtracking
			}
			
		}
		
		return false;
	}
	
	
	private static boolean isValidPlace(int[][] board, int row, int col, int n)
	{
		
		for(int r = row; r>=0; r--)
			if(board[r][col] == 1) return false;
		
		for(int r=row, c=col; r>=0 && c>=0; r--,c--)
		{
			if(board[r][c] == 1) return false;
		}
		
		for(int r = row, c=col; r>=0 && c < n; r--, c++)
		{
			if(board[r][c] == 1) return false;
		}
		
		return true;
	}

	public static void main(String args[])
	{
		
		int[][] board = {{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}};
		
		int n = board.length;

                        if(placeQueens(board, c, n))
			{
				for(int i=0; i < n; i++)
				{
					for(int j=0; j < n; j++)
						System.out.print(board[i][j]+" ");
					System.out.println();
				}
			}else
				System.out.println("Solution does not exist.");
         }

No comments:

Post a Comment