【问题标题】:How flaging element in a row with respect to other elements in other rows in a matrix in C#如何在 C# 中相对于矩阵中其他行中的其他元素标记行中的元素
【发布时间】:2017-11-27 23:44:15
【问题描述】:

我有以下矩形数组:

example

我需要检查是否有任何单元格从四面八方被零包围:水平、垂直和对角线,如示例中所示。

【问题讨论】:

  • 这是一场噩梦。您需要学习如何将代码划分为小函数!说processNeighbour( int row, int col)。有一条经验法则:一段代码不应超过一两个屏幕。 (有人说 5-10 行)
  • 您能否添加它给您的错误结果?它可能会帮助我们帮助您。

标签: c# arrays loops multidimensional-array


【解决方案1】:

这里有一个更好的方法

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[,] chromosome = {
                {1,0,1,1,1,0,1,1,1,1,},
                {1,0,1,1,1,1,1,1,1,0,},
                {1,0,0,0,0,1,0,0,0,0,},
                {0,1,0,1,0,1,0,1,1,1,},
                {1,1,1,1,0,0,1,1,1,1,},
                {1,1,1,1,0,1,1,1,0,0,},
                {1,1,0,0,0,0,0,1,1,1,},
                {1,0,1,1,0,0,0,1,1,0,},
                {1,1,0,0,0,0,0,0,0,0,},
                {0,0,0,1,0,0,0,1,0,0,}
                       };

            Boolean results11 = TestZero(chromosome, 1, 1);
            Boolean results85 = TestZero(chromosome, 8, 5);
        }

        static Boolean TestZero(int[,] array, int rowIndex, int colIndex)
        {
            if((rowIndex <= 0) || (rowIndex >= array.GetUpperBound(0)) || (colIndex <= 0) || (colIndex >= array.GetUpperBound(1))) return false;

            for(int i = rowIndex - 1; i <= rowIndex + 1; i++)
            {
                for(int j = colIndex - 1; j <= colIndex + 1; j++)
                {
                    if((i != rowIndex) && (j != colIndex))
                    {
                        if(array[i,j] == 1) return false;
                    }
                }
            }
            return true;
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多