C#中矩阵中其他行中其他元素的连续扩展元素如何

时间:2017-06-24 14:49:35

标签: c# arrays loops multidimensional-array

我有以下矩形数组:

enter image description here

example

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

1 个答案:

答案 0 :(得分:0)

这是一个更好的方法

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;
        }
    }
}