[美团]拜访
2017-05-06 18:25
169 查看
题目描述
现在有一个城市销售经理,需要从公司出发,去拜访市内的商家,已知他的位置以及商家的位置,但是由于城市道路交通的原因,他只能在左右中选择一个方向,在上下中选择一个方向,现在问他有多少种方案到达商家地址。给定一个地图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;
}
};
相关文章推荐
- 拜访-美团校招原题
- 拜访(动态规划)----美团2016研发工程师在线编程题
- 算法面试题-美团校招题(拜访)
- 美团-拜访-Java
- 动态规划-美团笔试题-拜访
- 美团 拜访
- 美团校招 拜访
- 牛客网---2016---美团拜访
- 拜访客户七大黄金定律
- “中国网络旗袍女”AnsheChung拜访CRD,洽谈与Dotman世界全面合作
- 用PAM完成用户和主机的Samba拜访节制
- 普京今夏将拜访老奶奶歌唱组合
- 美团2014校招笔试题
- [互联网面试笔试汇总C/C++-10] 糖果拆包-美团
- Android对ScrollView滚动监听,实现美团、大众点评的购买悬浮效果
- 基于Flume的美团日志收集系统(二)改进和优化
- 贝叶斯概率问题(美团笔试题)
- 2014年美团校招笔试题解(更新ING……)
- 【BZOJ】2060: [Usaco2010 Nov]Visiting Cows 拜访奶牛(树形dp)
- 美团性能分析框架和性能监控平台