problemscpp
A collection of my answers to algorithm problems in c++.
静态 Public 成员函数 | 所有成员列表
leetcode::shortest_path_in_binary_matrix::Solution类 参考

#include <leetcode.h>

静态 Public 成员函数

static int shortestPathBinaryMatrix (vector< vector< int > > &grid)
 

详细描述

在文件 leetcode.h2373 行定义.

成员函数说明

◆ shortestPathBinaryMatrix()

int leetcode::shortest_path_in_binary_matrix::Solution::shortestPathBinaryMatrix ( vector< vector< int > > &  grid)
static

在文件 leetcode.cpp6319 行定义.

6319 {
6320 int n = grid.size();
6321 auto levels = vector(n, vector(n, -1));
6322 auto cmp = [&n](const tuple<int, int, int> &t1, const tuple<int, int, int> &t2) {
6323 const auto &[level1, x1, y1] = t1;
6324 const auto &[level2, x2, y2] = t2;
6325 const int dx1 = abs(n - 1 - x1);
6326 const int dy1 = abs(n - 1 - y1);
6327 const int dx2 = abs(n - 1 - x2);
6328 const int dy2 = abs(n - 1 - y2);
6329 return level1 + dx1 + dy1 - min(dx1, dy1) > level2 + dx2 + dy2 - min(dx2, dy2);
6330 };
6331 priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, decltype(cmp)> pq(cmp);
6332 if(grid[0][0] == 0 && grid[n - 1][n - 1] == 0) {
6333 pq.push(make_tuple(1, 0, 0));
6334 } else {
6335 return -1;
6336 }
6337 while(!pq.empty()) {
6338 auto [level, x, y] = pq.top();
6339 if(x == n - 1 && y == n - 1) {
6340 return level;
6341 }
6342 pq.pop();
6343 if(levels[x][y] == -1 || levels[x][y] > level) {
6344 levels[x][y] = level;
6345 } else {
6346 continue;
6347 }
6348 pair<int, int> nexts[8] = {make_pair(x - 1, y - 1), make_pair(x - 1, y), make_pair(x - 1, y + 1),
6349 make_pair(x, y - 1), make_pair(x, y + 1),
6350 make_pair(x + 1, y - 1), make_pair(x + 1, y), make_pair(x + 1, y + 1)};
6351 for(auto [next_x, next_y]: nexts) {
6352 if(next_x >= 0 && next_x < n && next_y >= 0 && next_y < n && grid[next_x][next_y] == 0 && (levels[next_x][next_y] == -1 || levels[next_x][next_y] > level + 1)) {
6353 pq.push(make_tuple(level + 1, next_x, next_y));
6354 }
6355 }
6356 }
6357 return -1;
6358 }
bool cmp(const pair< int, int > &a, const pair< int, int > &b)
Definition: acwing.cpp:6470

引用了 acwing::acwing4397::cmp().


该类的文档由以下文件生成: