查詢C++中無限點的數量


在這個問題中,我們得到了一個二維陣列mat[n][m]。我們的任務是找到矩陣中無限點的數量。

如果矩陣的任何一個點的後續元素都是1,則稱該點為無限點。

mat[i][j] is endless when mat[i+1][j] … mat[n][j] and
mat[i][j+1] … mat[i][m] are 1.

讓我們來看一個例子來理解這個問題:

輸入

mat[][] = {0, 0}
{1, 1}

輸出

2

解釋

元素mat[0][1]和mat[1][1]是無限的。

解決方案方法

解決這個問題的一個簡單方法是迭代矩陣的所有元素。並對每個元素檢查當前元素是否無限。如果是,則增加計數。檢查陣列的所有元素後返回計數。

高效方法

為了解決這個問題,我們將使用動態規劃來檢查元素是否無限。為了使其無限,其行和列之後的所有元素都需要為1。

因此,我們將使用兩個DP矩陣來計算每個索引的無限下一行和無限下一列。並檢查每個位置,如果該位置具有無限的下一行和下一列。然後返回無限元素的計數。

程式說明了我們解決方案的工作原理:

示例

 線上演示

#include <iostream>
#include <math.h>
using namespace std;
const int monthDays[12] = { 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
int countLeapYearDays(int d[]){
   int years = d[2];
   if (d[1] <= 2)
      years--;
   return ( (years / 4) - (years / 100) + (years / 400) );
}
int countNoOfDays(int date1[], int date2[]){
   long int dayCount1 = (date1[2] * 365);
   dayCount1 += monthDays[date1[1]];
   dayCount1 += date1[0];
   dayCount1 += countLeapYearDays(date1);
   long int dayCount2 = (date2[2] * 365);
   dayCount2 += monthDays[date2[1]];
   dayCount2 += date2[0];
   dayCount2 += countLeapYearDays(date2);
   return ( abs(dayCount1 - dayCount2) );
}
int main(){
   int date1[3] = {13, 3, 2021};
   int date2[3] = {24, 5, 2023};
   cout<<"The number of days between two dates is "<<countNoOfDays(date1, date2);
   return 0;
}

輸出

The number of days between two dates is 802

更新於:2021年3月15日

68 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.