基于Monster 组和GPT的调写:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
int[,] matrix = {
{ 0, 1, 0 },
{ 1, 0, 1 },
{ 1, 0, 0 },
{ 0, 1, 0 }
};
int minRows = matrix.GetLength(0);
var solutions = new List<List<int>>();
FindCombinations(matrix, new List<int>(), 0, solutions, ref minRows);
// 打印所有解决方案
foreach(var solution in solutions)
{
foreach(var row in solution)
{
Console.Write((char)('A' + row));
}
Console.WriteLine();
}
}
static void FindCombinations(int[,] matrix, List<int> current, int start, List<List<int>> solutions, ref int minRows)
{
if (current.Count > minRows)
return;
if (IsValidCombination(matrix, current))
{
if (current.Count < minRows)
{
solutions.Clear();
minRows = current.Count;
}
solutions.Add(new List<int>(current));
// 不要在这里返回; 继续寻找其他可能的解决方案
}
for (int i = start; i < matrix.GetLength(0); i++)
{
current.Add(i);
FindCombinations(matrix, current, i + 1, solutions, ref minRows);
current.RemoveAt(current.Count - 1);
}
}
static bool IsValidCombination(int[,] matrix, List<int> combination)
{
if (combination.Count == 0) return false;
for (int col = 0; col < matrix.GetLength(1); col++)
{
bool hasZero = false;
foreach (int row in combination)
{
if (matrix[row, col] == 0)
{
hasZero = true;
break;
}
}
if (!hasZero) return false;
}
return true;
}
}