Find number of endless points in C++

C++Server Side ProgrammingProgramming

In this problem, we are given two dimensional arrays mat[n][m]. Our task is to find the number of endless points in the matrix.

Any point of the matrix is said to be endless if its next elements are 1. i.e.

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

Let’s take an example to understand the problem,


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




Element mat[0][1] and mat[1][1] are endless.

Solution Approach

A simple solution to the problem is by iterating all elements of the matrix. And for each element check if the current element is endless or not. If yes, increase count. Return the count after checking all elements of the array.

Efficient Approach

To solve the problem, we will use dynamic programming to check if elements are endless or not. For it to be endless all elements of its row and columns after it need to be 1.

So, we will use two DP matrices to count endless next row and endless next columns for each index. And the check of each position, if the position has the next endless row and column. Then return the count of endless elements.

Program to illustrate the working of our solution,


 Live Demo

#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)
   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
Published on 15-Mar-2021 10:53:37