C#练习题答案: 数独解决方案验证器【难度:4级】--景越C#经典编程题库,1000道C#基础练习题等你来挑战

这篇博客详细介绍了10种不同的C#编程解法,用于验证数独解决方案的正确性,难度级别为4级。内容涵盖了各种算法和逻辑思路,适合C#编程学习者和面试准备者提升技能。
摘要由CSDN通过智能技术生成

数独解决方案验证器【难度:4级】:

答案1:

using System;
using System.Collections.Generic;
using System.Linq;

public class Sudoku
{
   
    private static int[] nineNumbers = new int[] {
    1, 2, 3, 4, 5, 6, 7, 8, 9 };
    
    public static bool ValidateSolution(int[][] board)
    {
   
        for (int i = 0; i < 9; ++i)
        {
   
            var row = new List<int>();
            for (int j = 0; j < 9; ++j) row.Add(board[i][j]);
            if (!ValidateNine(row)) return false;

            var col = new List<int>();
            for (int j = 0; j < 9; ++j) col.Add(board[j][i]);
            if (!ValidateNine(col)) return false;

            var block = new List<int>();
            int br = (i / 3) * 3;
            int bc = (i % 3) * 3;
            for (int j = 0; j < 9; ++j) block.Add(board[br + j / 3][bc + j % 3]);
            if (!ValidateNine(block)) return false;
        }

        return true;
    }

    private static bool ValidateNine(IList<int> nine)
    {
   
        return nineNumbers.All(nine.Contains);
    }
}

答案2:

using System.Linq;
using System.Collections.Generic;
public class Sudoku
{
   
  public static bool ValidateSolution(int[][] board)
  {
   
    if (board.SelectMany(row => row).Any(x => x == 0))
      return false;
    
    return Enumerable.Range(0,9).All(i => 
      CellsInRow(board, i).Distinct().Count() == 9
      &amp;&amp; CellsInCol(board, i).Distinct().Count() == 9
      &amp;&amp; CellsInBox(board, i).Distinct().Count() == 9
    );
  }

  static IEnumerable<int> CellsInRow(int[][] board, int row) => board[row];
  static IEnumerable<int> CellsInCol(int[][] board, int col) => board.Select(row => row[col]);
  static IEnumerable<int> CellsInBox(int[][] board, int box) =>  Enumerable.Range(0, 9
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值