Skip to content

Instantly share code, notes, and snippets.

@Ghostscypher
Created December 24, 2023 06:08
Show Gist options
  • Save Ghostscypher/aef4860257830a3c97f986619cb467ec to your computer and use it in GitHub Desktop.
Save Ghostscypher/aef4860257830a3c97f986619cb467ec to your computer and use it in GitHub Desktop.
Grid Path problem
<?php
require_once __DIR__ . "/include.php";
// This shows how many ways we can go from the top left corner to the bottom right corner in a M x N grid
function grid_paths($m, $n)
{
// Use memoization to avoid repeated calculations
$memo = [];
for($i = 0; $i < $m; $i++)
{
for($j = 0; $j < $n; $j++)
{
if($i == 0 || $j == 0)
{
$memo[$i][$j] = 1;
}
else
{
$memo[$i][$j] = $memo[$i - 1][$j] + $memo[$i][$j - 1];
}
}
}
return $memo[$m - 1][$n - 1];
}
// The mathematically correct way to do this is to use the formula (m + n - 2)! / (m - 1)! (n - 1)!
function grid_paths_math($m, $n)
{
$factorial = function($n) {
$result = 1;
for($i = 1; $i <= $n; $i++)
{
$result *= $i;
}
return $result;
};
return $factorial($m + $n - 2) / ($factorial($m - 1) * $factorial($n - 1));
}
$m = 5;
$n = 4;
echo grid_paths($m, $n);
echo "\n";
echo grid_paths_math($m, $n);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment