Skip to content

Instantly share code, notes, and snippets.

@fintara
Last active January 1, 2016 20:19
Show Gist options
  • Save fintara/8195908 to your computer and use it in GitHub Desktop.
Save fintara/8195908 to your computer and use it in GitHub Desktop.
We are given a matrix, in which we should count the steps of a path of a given number.
<?php
/**
* Maze.php
*
* We are given a matrix, in which we should count the steps of a path of a given number.
*
* @author Tsvetan Ovedenski
*/
// matrix
$maze = [
[1,2,3,4],
[3,2,2,1],
[7,5,2,4],
[4,3,2,6],
];
$cnt = 0; // count of num found
$num = 2; // what we are looking for
for ($row = 0; $row < count($maze) - 1; $row++) {
for ($col = 0; $col < count($maze[$row]) - 1; $col++) {
if ($maze[$row][$col] === $num) { // we've got our number,
while (1) { // start following the path
$cnt++;
if ($row === count($maze) - 1 || $col === count($maze[$row]) - 1)
break;
if ($maze[$row][$col + 1] === $num) {
$col++;
} else if ($maze[$row + 1][$col] === $num) {
$row++;
}
}
break;
}
}
}
echo $cnt; // result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment