15 August 2017

sudoku2

My solution:
bool sudoku2(char[][] grid) 
{
    var columnList = new List<Dictionary<char, int>>();
    var rowList = new List<Dictionary<char, int>>();
    var nineList = new List<Dictionary<char, int>>();
    foreach (var t in grid)
    {
        var dict = new Dictionary<char, int>();
        for (var j = 0; j < grid[0].Length; j++)
            if (dict.ContainsKey(t[j]))
                dict[t[j]]++;
            else
                dict[t[j]] = 1;

        rowList.Add(dict);
    }

    if (rowList.Any(d => d.Count(pair => pair.Key != '.' && pair.Value > 1) > 0))
        return false;

    for (var i = 0; i < grid.Length; i++)
    {
        var dict = new Dictionary<char, int>();
        for (var j = 0; j < grid[0].Length; j++)
            if (dict.ContainsKey(grid[j][i]))
                dict[grid[j][i]]++;
            else
                dict[grid[j][i]] = 1;

        columnList.Add(dict);
    }

    if (columnList.Any(d => d.Count(pair => pair.Key != '.' && pair.Value > 1) > 0))
        return false;

    for (var i = 0; i < grid.Length / 3; i++)
    {
        for (var j = 0; j < grid[0].Length / 3; j++)
        {
            var dict = new Dictionary<char, int>();
            if (dict.ContainsKey(grid[i * 3][j * 3]))
                dict[grid[i * 3][j * 3]]++;
            else
                dict[grid[i * 3][j * 3]] = 1;

            if (dict.ContainsKey(grid[i * 3][j * 3 + 1]))
                dict[grid[i * 3][j * 3 + 1]]++;
            else
                dict[grid[i * 3][j * 3 + 1]] = 1;

            if (dict.ContainsKey(grid[i * 3][j * 3 + 2]))
                dict[grid[i * 3][j * 3 + 2]]++;
            else
                dict[grid[i * 3][j * 3 + 2]] = 1;

            if (dict.ContainsKey(grid[i * 3 + 1][j * 3]))
                dict[grid[i * 3 + 1][j * 3]]++;
            else
                dict[grid[i * 3 + 1][j * 3]] = 1;

            if (dict.ContainsKey(grid[i * 3 + 1][j * 3 + 1]))
                dict[grid[i * 3 + 1][j * 3 + 1]]++;
            else
                dict[grid[i * 3 + 1][j * 3 + 1]] = 1;

            if (dict.ContainsKey(grid[i * 3 + 1][j * 3 + 2]))
                dict[grid[i * 3 + 1][j * 3 + 2]]++;
            else
                dict[grid[i * 3 + 1][j * 3 + 2]] = 1;

            if (dict.ContainsKey(grid[i * 3 + 2][j * 3]))
                dict[grid[i * 3 + 2][j * 3]]++;
            else
                dict[grid[i * 3 + 2][j * 3]] = 1;

            if (dict.ContainsKey(grid[i * 3 + 2][j * 3 + 1]))
                dict[grid[i * 3 + 2][j * 3 + 1]]++;
            else
                dict[grid[i * 3 + 2][j * 3 + 1]] = 1;

            if (dict.ContainsKey(grid[i * 3 + 2][j * 3 + 2]))
                dict[grid[i * 3 + 2][j * 3 + 2]]++;
            else
                dict[grid[i * 3 + 2][j * 3 + 2]] = 1;

            nineList.Add(dict);
        }
    }

    return !nineList.Any(d => d.Count(pair => pair.Key != '.' && pair.Value > 1) > 0);
}

Previous Next