新农上路
- 积分
- 93
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2017-2-5
- 最后登录
- 1970-1-1
|
[quote]hxuanyu 发表于 2018-8-20 20:22
- class maze {
- public:
- int minPathSum(vector& grid, int x, int y) {
- [/quote]
- 哈哈,才看到真题,原来target不一定在右下角,这样可以4个方向查找,重新写了一遍,lz能帮我看看吗 谢啦
- [code]
- class maze {
- public:
- int minPathSum(vector<vector<int>>& grid) {
- if (grid[0][0] == 0) return -1;
- vector<vector<bool>> visited(grid.size(), vector<bool>(grid[0].size(), false));
- queue<pair<int, int>> que;
- que.push(make_pair(0, 0));
- visited[0][0] = true;
- vector<vector<int>> dirs = { {-1, 0}, {0, 1}, {1,0},{0, -1} };
- int dis = 1;
- while (!que.empty()) {
- int size = que.size();
- for (int i = 0; i < size; i++) {
- auto top = que.front();
- que.pop();
-
- if (grid[top.first][top.second] == 9) return dis;
- for (auto dir : dirs) {
- int newx = top.first + dir[0];
- int newy = top.second + dir[1];
- if ((newx < 0) || (newy < 0) || (newx >= grid.size()) || (newy >= grid[0].size()) || (grid[newx][newy] == 0)) continue;
- que.push(make_pair(newx, newy));
- visited[newx][newy] = true;
- }
- }
- dis++;
- }
- return -1;
- }
- };
复制代码
|
|