现在有一个城市销售经理,需要从公司出发,去拜访市内的商家,已知他的位置以及商家的位置,但是由于城市道路交通的原因,他只能在左右中选择一个方向,在上下中选择一个方向,现在问他有多少种方案到达商家地址。
给定一个地图map及它的长宽n和m,其中1代表经理位置,2代表商家位置,-1代表不能经过的地区,0代表可以经过的地区,请返回方案数,保证一定存在合法路径。保证矩阵的长宽都小于等于10。
测试样例: [[0,1,0],[2,0,0]],2,3 返回:2 这个题目的描述标亮的地方有迷惑性,结合所给的例子,应该理解到整个过程中只能走左右方向中的一个,上下方向中的一个,所以要先遍历地图,找到经理和商家的位置,判断他们的方位关系,就可以确定走向,那么动态规划的递推公式也就出来了。注意,后来才发现对这种不适用,但是牛客测试用例没有这种情况:
2 0 0
0 0 -1
0 0 1
solution那里应该初始化为:
1 1 0 1 1 1
1 1 0 而不是 1 1 0
1 1 1 1 1 1
class Visit { public: int countPath(vector<vector<int> > map, int n, int m) { int res = 0; int r_man = 0, c_man = 0; int r_bus = 0, c_bus = 0; vector<int> tmp_row(m, 1); vector<vector<int> > solution(n, tmp_row); int neighr = 0, neighc = 0; //先定位经理和商家的位置 for (int i = 0; i<n; i++){ for (int j = 0; j<m; j++){ if (map[i][j] == 1){ r_man = i; c_man = j; } if (map[i][j] == 2){ r_bus = i; c_bus = j; } if (map[i][j] == -1) solution[i][j] = 0; } } //确定搜索的方向 if (r_man == r_bus || c_man == c_bus) return 1; neighr=r_man<r_bus?-1:1; neighc=c_man<c_bus?-1:1; //动态规划 for (int i = r_man - neighr; r_man<r_bus ? i <= r_bus : i >= r_bus; i -= neighr){ for (int j = c_man - neighc; c_man<c_bus ? j <= c_bus : j >= c_bus; j -= neighc){ solution[i][j] = solution[i + neighr][j] + solution[i][j + neighc]; } } res = solution[r_bus][c_bus]; return res; } };