1. 概述

一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。

问总共有多少条不同的路径?

2. 解题

  1. <?php
  2. class Solution {
  3. public $way = [];
  4. public $map = [];
  5. /**
  6. * @param Integer $m 列
  7. * @param Integer $n 行
  8. * @return Integer
  9. */
  10. public function uniquePaths($m, $n) {
  11. if (($m <= 0) && ($n <= 0)) {
  12. $this->way[] = [];
  13. } elseif (($m <= 0 && $n > 0) || ($m > 0 && $n <= 0)) {
  14. $forward = $m > 0 ? 'r' : 'd';
  15. $way = str_repeat($forward, max($m, $n));
  16. $way = explode(',', $way);
  17. $this->way[] = $way;
  18. } else {
  19. $map = [];
  20. for ($i = 0; $i < $n; $i++) {
  21. for ($j = 0; $j < $m; $j++) {
  22. $map[$i][$j] = 1;
  23. }
  24. }
  25. $this->map = $map;
  26. $this->dp ($n, $m, [0, 0]);
  27. }
  28. return count($this->way);
  29. }
  30. private function dp ($n, $m, $last, $way = []) {
  31. if ($last == [$n - 1, $m - 1]) {
  32. $this->way[] = $way;
  33. return;
  34. }
  35. if (isset($this->map[$last[0]][$last[1] + 1])) { // 右
  36. $way[] = 'r';
  37. $this->dp($n, $m, [$last[0], $last[1] + 1], $way);
  38. array_pop($way);
  39. }
  40. if (isset($this->map[$last[0] + 1][$last[1]])) { // 下
  41. $way[] = 'd';
  42. $this->dp($n, $m, [$last[0] + 1, $last[1]], $way);
  43. array_pop($way);
  44. }
  45. }
  46. }
  47. $m = 0;
  48. $n = 3;
  49. $cls = new Solution();
  50. $r = $cls->uniquePaths($m, $n);
  51. echo $r;
  52. array_walk($cls->map, function(&$v) {
  53. $v = implode(',', $v);
  54. });
  55. print_r($cls->map);
  56. array_walk($cls->way, function(&$v) {
  57. $v = implode(',', $v);
  58. });
  59. print_r($cls->way);