搜索2D M x M阵列C#的所有对角线的方法

时间:2014-07-04 08:04:07

标签: c# arrays algorithm linq asymptotic-complexity

我已经开始编写一段代码来帮助我在M x M 2D阵列的对角线中找到的所有对象中搜索对象。虽然代码有效,但我想知道是否有一种方法可以改进它,或者存在一种不同的技术,我可以用更少的代码行来实现相同的结果。只是不想重新发明轮子。 :)

 bool allDiagonals(string[] board, string strToFind)//board must be a square matrix
    {
        string s = "";
        for (int col = board[0].Length - 1; col >= 0; col--)
        {

            int row = 0;
            int j = col;
            s = "";
            while (j <= board[0].Length - 1)
            {
                s += board[row++][j++];
            }
            if (s.Contains(strToFind))
                return true;
        }

        for (int row = board.Length - 1; row > 0; row--)
        {
            int colmin = 0;
            s = "";
            for (int i = row; i < board.Length; i++)
            {
                s += board[i][colmin++];
            }
            if (s.Contains(strToFind))
                return true;
        }

        for (int col = 0; col <= board[0].Length - 1; col++)
        {

            int row = 0;
            int j = col;
            s = "";
            while (j >= 0)
            {
                s += board[row++][j--];
            }
            if (s.Contains(strToFind))
                return true;
        }
        for (int row = board.Length - 1; row > 0; row--)
        {
            s = "";
            int colmax = board[0].Length - 1;
            //scan from bottom right to main diagonal
            for (int i = row; i < board.Length; i++)
            {
                s += board[i][colmax--];
            }
            if (s.Contains(strToFind))
                return true;
        }
        return false;
}

0 个答案:

没有答案