Monday, August 13, 2012

Program 1 : Sudoku Solver

C# Programming
C# Programming



PROBLEM STATEMENT :

Input :

The first line contains N,K. The following K lines contain 3 numbers: x, y and d. 1 <= x,y,d <= N^2. This means that a number d is present on the board at position (x,y) 2 <= N <= 30 0 <= K <= N4 At most 50% of the board will be covered at the start. All positions (x,y) in the input will be unique.

Output :

The output consists of N2 rows having N2 numbers each. Each number should be between 1 and N2 (inclusive) and separated by a space. If the initial grid has a number d at position (x,y), then even the output should have the number d at position (x,y).

Scoring :

  • For each row and every number K in the range 1 to N2 that is missing from the row, incurs a penalty of 1.
  • For each column and every number K in the range 1 to N2 that is missing from the column, incurs a penalty of 1.
  • Similarly, for each box and every number K in the range 1 to N2 that is missing from the box, incurs a penalty of 1.
A box (as explained above) is a N X N square and the grid can be divided into N2 such non-overlapping boxes.
Solution :

using System;
using System.Text;

namespace PracticeProblem
{
    //SUDOKU SOLVER
    class Program
    {
        public static int Logic1(int row, int col, int n)
        {
            int n2 = n * n;
            int value = (row / n + row * n + col) % n2;
            return value > 0 ? value : n2;
        }

        static void Main(string[] args)
        {
            int x, y, d;
            int[,] matrix;

            //Input
            string value = Console.ReadLine();
            string[] arr = value.Split(' ');
            int n = Int32.Parse(arr[0]);
            int k = Int32.Parse(arr[1]);
            int n2 = n * n;
            matrix = new int[n2, n2];

            for (int i = 0; i < k; i++)
            {
                string val = Console.ReadLine();
                string[] data = val.Split(' ');
                x = Int32.Parse(data[0]);
                y = Int32.Parse(data[1]);
                d = Int32.Parse(data[2]);
                matrix[x - 1, y - 1] = d;
            }

            //Output
            for (int row = 0; row < n2; row++)
            {
                for (int col = 0; col < n2; col++)
                {
                    if (matrix[row, col] == 0)
                    {
                        matrix[row, col] = Logic1(row, col, n);
                        Console.Write(matrix[row, col] + " ");
                    }
                    else
                    {
                        Console.Write(matrix[row, col] + " ");
                    }
                }
                Console.Write("\n");
            }
            Console.ReadKey();
        }
    }
}

NOTE : Problem is taken from CodeChef.

No comments:

Post a Comment