C++ 中檢查矩陣是否為上三角形的程式


給定一個方陣 M[r][c],其中“r”是行數,“c”是列數,且 r = c,我們要檢查“M”是否是上三角形矩陣。

上三角形矩陣

上三角形矩陣是指主對角線(包括主對角線)以上元素不為零,以下元素都為零的矩陣。

例如以下示例 −

在上圖中,以紅色高亮的元素是主對角線以下的元素,都為零,而其餘元素都非零。

示例

Input: m[3][3] = { {1, 2, 3},
   {0, 5, 6},
   {0, 0, 9}}
Output: yes
Input: m[3][3] == { {3, 0, 1},
   {6, 2, 0},
   {7, 5, 3} }
Output: no

演算法

Start
Step 1 -> define macro as #define size 4
Step 2 -> Declare function to check matrix is lower triangular matrix
   bool check(int arr[size][size])
      Loop For int i = 1 and i < size and i++
         Loop For int j = 0 and j < i and j++
            IF (arr[i][j] != 0)
               return false
            End
      End
   End
   Return true
Step 3 -> In main()
   Declare int arr[size][size] = { { 1, 1, 3, 2 },
      { 0, 3, 3, 2 },
      { 0, 0, 2, 1 },
      { 0, 0, 0, 1 } }
   IF (check(arr))
      Print its a lower triangular matrix
   End
   Else
      Print its not a lower triangular matrix
   End
Stop

示例

#include <bits/stdc++.h>
#define size 4
using namespace std;
// check matrix is lower triangular matrix
bool check(int arr[size][size]){
   for (int i = 1; i < size; i++)
      for (int j = 0; j < i; j++)
         if (arr[i][j] != 0)
            return false;
   return true;
}
int main(){
   int arr[size][size] = { { 1, 1, 3, 2 },
      { 0, 3, 3, 2 },
      { 0, 0, 2, 1 },
      { 0, 0, 0, 1 } };
   if (check(arr))
      cout << "its a lower triangular matrix";
   else
      cout << "its not a lower triangular matrix";
   return 0;
}

輸出

its a lower triangular matrix

更新於:2019 年 9 月 23 日

721 次檢視

開啟您的 職業

完成課程即可獲得認證

開始
廣告