C# 鸡兔同笼 数字瘦身简化版本 洞穴扫描(相连算一个)

段兴为
2023-12-01
  /// <summary>
    /// 鸡兔同笼,头共35个,脚共100只,鸡兔各有多少只?
    /// 还是活用for循环 35个头 已知 数学问题2i+4k=100
    /// </summary>
    static void ChickenRabbit()
    {
        for (int i = 1; i < 35; i++)//i为鸡的数量
        {
            int k = 35 - i;//k为兔的数量
            if (2 * i + k * 4 == 100)//脚100只
            {
                Console.WriteLine("鸡={0},兔={1}", i, k);
            }
        }
    }
    /// <summary>
    /// 数字瘦身
    /// 比如:8967 = 8+9+6+7 = 30 = 3+0 = 3
    /// 比如:158 = 1+5+8 = 14 = 1+4 = 5
    /// </summary>
    static void DigitalSlimming()
    {
        Console.WriteLine("请输入一个整形数字:");
        int number = int.Parse(Console.ReadLine());
        while (number / 10 != 0)//如果不是个位数就执行
        {
            int sum = 0;
            while (number > 0)
            {
                sum += number % 10;//取个位 累加
                number /= 10;//取完了值 该削位了
            }
            number = sum;
        }
        Console.WriteLine(number);
    }

  洞穴题 大概就是有这么一块区域 有几个洞找到一个洞扫描 旁边的洞 连着的算一个类型的洞

class Program
{
    static void Main(string[] args)
    {
        GetHoleNumber();
    }
    static void GetHoleNumber()
    {
        int count = 1;//洞穴的类型
        int[,] blocks = {
                {1,0,1,0,1},
                {1,0,1,1,1},
                {1,1,1,0,1},
                {1,0,1,1,1},
                {1,1,0,1,0}
            };

        for (int i = 0; i < 5; i++)
        {
            for (int j = 0; j < 5; j++)
            {
                if (blocks[i, j] == 0)
                {
                    count++;
                    blocks[i, j] = count;
                    CheckArround(blocks, i, j,count);
                }
            }
        }
        for (int i = 0; i < 5; i++)
        {
            for (int j = 0; j < 5; j++)
            {
                Console.Write(blocks[i,j]+",");
            }
            Console.WriteLine();
        }
        Console.WriteLine($"一共有{count-1}个洞穴(相连的算一个)");//count起始是1所以-1

    }
    /// <summary>
    /// 通过递归改变是洞穴的值
    /// </summary>
    /// <param name="blocks"></param>
    /// <param name="posX"></param>
    /// <param name="posY"></param>
    /// <param name="typeArround">第几种类型的洞穴</param>
    static void CheckArround(int[,] blocks, int posX, int posY,int typeArround)
    {
        for (int i = -1; i <= 1; i++)
        {
            for (int j = -1; j <= 1; j++)
            {
                if (posX + i >= 0 && posX + i < 5 && posY + j >= 0 && posY + j < 5)
                {
                    if (blocks[posX + i, posY + j] == 0)//扫描周围有洞穴么如果有标出
                    {
                        blocks[posX + i, posY + j] = typeArround;
                        CheckArround(blocks, posX + i, posY + j, typeArround);
                    }
                }
            }
        }
    }
}

 

 

 

 类似资料: