首页 > 文章列表 > 打印矩阵边界元素的Python程序

打印矩阵边界元素的Python程序

矩阵 打印 边界元素
378 2023-08-31

Boundary Elements of a Matrix

没有被属于同一矩阵的其他元素包围的元素被称为边界元素。利用这个现象,我们可以构建一个程序。让我们考虑一个输入输出的场景,然后构建一个程序。

输入输出场景

考虑一个矩阵(方阵)

  • The Boundary elements are the elements except the middle elements of the matrix.

  • 矩阵的中间元素是5,除了5之外没有其他中间元素。

  • So, the Boundary elements are 9, 8, 7, 6, 4, 3, 2, and 1 as they are lying in the boundary positions of the matrix.

9  8  7
6  5  4
3  2  1

算法

  • Step 1 − Starting from the initial element of the matrix, traverse the elements of the array, which represents a matrix.

  • 第二步 − 我们使用二维数组遍历矩阵的元素,其中一个维度表示行,另一个维度表示列。因此,外部循环表示矩阵的行,内部循环表示矩阵的列。

  • 步骤 3 - 如果元素属于第一行或最后一行或第一列或最后一列,则该元素可以被视为边界元素并可以打印。

  • 第四步 - 如果不是,则该元素必须被视为非边界元素,并应该被跳过。在这种情况下,应该打印一个空格代替非边界元素。

Example

In the following example, we are going to discuss about the process of finding the boundary elements in a matrix.

def functionToPrint(arra, r, c):
   for i in range(r):
      for j in range(c):
         if (i == 0):
            print(arra[i][j])
         elif (i == r-1):
            print(arra[i][j]) 
         elif (j == 0):
            print(arra[i][j])
         elif (j == c-1):
            print(arra[i][j])
         else:
            print(" ")

if __name__ == "__main__":
   arra = [[1, 2, 3, 4], [5, 6, 7, 8],
      [9, 10, 11, 12], [13, 14, 15, 16]]

   print("The boundary elements of the given matrix are: ")
   functionToPrint(arra, 4, 4)

Output

上述程序的输出如下:

The boundary elements of the given matrix are: 
1
2
3
4
5


8
9


12
13
14
15
16