题目:
写程序判断一个9*9的数字盘面是否为合法的数独(查看定义)。 9*9的盘面按照Row-major order表示为一个81维的一维数组。 提示:请直接在一维数组上操作,不要先将一维数组拷贝到9*9的二维数组。
Code:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; namespace Sudoku { class Program { static void Main(string[] args) { int[] intArr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 3, 4, 5, 6, 7, 8, 9, 1, 3, 4, 5, 6, 7, 8, 9, 1, 2, 4, 5, 6, 7, 8, 9, 1, 2, 3, 5, 6, 7, 8, 9, 1, 2, 3, 4, 6, 7, 8, 9, 1, 2, 3, 4, 5, 7, 8, 9, 1, 2, 3, 4, 5, 6, 8, 9, 1, 2, 3, 4, 5, 6, 7, 9, 1, 2, 3, 4, 5, 6, 7, 8}; Console.WriteLine(IsSudoku(intArr)); } static bool IsSudoku(int[] intArr) { int n = (int)(Math.Sqrt(intArr.Length)); if (n * n != intArr.Length) { throw new Exception("Intput array is not meet requirement: Length doesn't equals n*n."); } Hashtable ht = new Hashtable(); int count = 0; int sum = 45; //from 1 to 9, sum is 45; for (int i = 0; i < n; i++) { for (int j = i * n; j < i * n + n; j++) { if (ht[intArr[j]]== null) { ht.Add(intArr[j], true); count += intArr[j]; } else { return false; } } if (count != sum) { return false; } count = 0; ht.Clear(); } for (int i = 0; i<n; i++) { for (int j = i; j < n*n; j=j+n) { if (ht[intArr[j]] == null) { ht.Add(intArr[j], true); count += intArr[j]; } else { return false; } } if (count!=sum) { return false; } count = 0; ht.Clear(); } return true; } } }