ADS
Algorithms and Data Structures
Loading...
Searching...
No Matches
GridPaths.h File Reference

Two problems of dynamic programming on a matrix of \( m \) rows and \( n \) columns, each cell solved from its neighbors above and to the left: More...

#include "ADS/Contract.h"
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <vector>
#include "ADS/optimization/impl/GridPaths.tpp"

Go to the source code of this file.

Classes

struct  ADS::GridSquare
 a square of a matrix: its side and its upper left cell More...

Namespaces

namespace  ADS

Functions

template<class T>
GridSquare ADS::largestSquare (const std::vector< std::vector< T > > &A)
 the largest square of nonzero cells of \( A \), the first in the order of the rows of its lower right cell
template<class C = std::uint64_t, class T>
C ADS::countLatticePaths (const std::vector< std::vector< T > > &B)
 the number of the paths from the upper left to the lower right cell of \( B \), each step right or down, through nonzero cells only; 0 for \( B \) empty

Detailed description

Two problems of dynamic programming on a matrix of \( m \) rows and \( n \) columns, each cell solved from its neighbors above and to the left:

  • largestSquare(): the largest square of nonzero cells of a 0/1 matrix. With \( S[ i ][ j ] \) the side of the largest one with its lower right corner in \( ( i , j ) \), \( S[ i ][ j ] = 0 \) on a zero cell and otherwise 1 plus the least of \( S[ i - 1 ][ j ] \), \( S[ i - 1 ][ j - 1 ] \) and \( S[ i ][ j - 1 ] \), since the three squares cover all the square of side one more but its corner; \( \Theta( m n ) \) time, \( \Theta( n ) \) space keeping one row. The largest rectangle of ones takes \( \Theta( m n ) \) too, by the largest rectangle in the histogram of each row;
  • countLatticePaths(): the monotone lattice paths from the upper left to the lower right cell, a step right or down, through the nonzero cells: \( N[ i ][ j ] = N[ i - 1 ][ j ] + N[ i ][ j - 1 ] \) on a free cell and 0 on a blocked one, \( \Theta( m n ) \) time and \( \Theta( n ) \) space. With no blocked cell they are \( \binom{m + n - 2}{m - 1} \); with few blocked cells, the inclusion-exclusion on the blocked cells sorted takes \( O( b^2 ) \) binomials for \( b \) of them.

The contracts [see Contract.h]: the matrix is a rectangle; the square found is inside the matrix and all nonzero (checked at level 3). The functions are defined in GridPaths.tpp.

See also
A. Montresor, Algoritmi e Strutture Dati, 2025, chapter 13, the Esercizi vari and the Esercizi Programmazione dinamica, https://algoritmicamente.it/materiali/libro/capitoli/cap13.pdf
S. S. Skiena, M. A. Revilla, Programming Challenges, Springer, 2003, chapters 6 and 11
Author
Donato Meoli
Dipartimento di Informatica
Università di Pisa