使用 C++ 中的矩陣計算所有排序行數


在本教程中,我們將討論一個程式,此程式用於查詢矩陣中所有已排序行數。

為此,我們需提供 m*n 矩陣。我們的任務是計算給定矩陣中按升序或降序排序的所有行。

示例

 即時演示

#include <bits/stdc++.h>
#define MAX 100
using namespace std;
//counting sorted rows
int count_srows(int mat[][MAX], int r, int c){
   int result = 0;
   for (int i=0; i<r; i++){
      int j;
      for (j=0; j<c-1; j++)
      if (mat[i][j+1] <= mat[i][j])
         break;
      if (j == c-1)
         result++;
   }
   for (int i=0; i<r; i++){
      int j;
      for (j=c-1; j>0; j--)
         if (mat[i][j-1] <= mat[i][j])
            break;
      if (c > 1 && j == 0)
         result++;
   }
   return result;
}
   int main(){
   int m = 4, n = 5;
   int mat[][MAX] = {{1, 2, 3, 4, 5}, {  4, 3, 1, 2, 6}, {8, 7, 6, 5, 4}, {5, 7, 8, 9, 10}};
   cout << count_srows(mat, m, n);
   return 0;
}

輸出

3

更新於:17-Feb-2020

160 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.