首頁  >  文章  >  後端開發  >  列印矩陣邊界元素的Python程序

列印矩陣邊界元素的Python程序

WBOY
WBOY轉載
2023-08-26 14:01:06608瀏覽

列印矩陣邊界元素的Python程序

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

以上是列印矩陣邊界元素的Python程序的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除