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

#include <leetcode.h>

静态 Public 成员函数

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

详细描述

在文件 leetcode.h2940 行定义.

成员函数说明

◆ minCost()

int leetcode::minimum_cost_to_make_at_least_one_valid_path_in_a_grid::Solution::minCost ( vector< vector< int > > &  grid)
static

在文件 leetcode.cpp8142 行定义.

8142 {
8143 const int m = grid.size();
8144 const int n = grid[0].size();
8145 vector g(m, vector<Node *>(n, nullptr));
8146 for(int i = 0; i < m; i++) {
8147 for(int j = 0; j < n; j++) {
8148 g[i][j] = new Node(i, j);
8149 }
8150 }
8151 for(int i = 0; i < m; i++) {
8152 for(int j = 0; j < n; j++) {
8153 pair<int, int> nexts[4] = {{i + 1, j}, {i - 1, j}, {i, j + 1}, {i, j - 1}};
8154 for(auto [x, y]: nexts) {
8155 if(x >= 0 && x < m && y >= 0 && y < n) {
8156 g[i][j]->siblings.insert(make_pair(g[x][y], 1));
8157 }
8158 }
8159 int x = i;
8160 int y = j;
8161 switch(grid[i][j]) {
8162 case 1:
8163 y++;
8164 break;
8165 case 2:
8166 y--;
8167 break;
8168 case 3:
8169 x++;
8170 break;
8171 case 4:
8172 x--;
8173 break;
8174 }
8175 if(x >= 0 && x < m && y >= 0 && y < n) {
8176 g[i][j]->siblings[g[x][y]] = 0;
8177 }
8178 }
8179 }
8180 priority_queue<pair<int, Node *>, vector<pair<int, Node *>>, mycmp> pq;
8181 unordered_set<Node *> vis;
8182 pq.push({0, g[0][0]});
8183 while(!pq.empty()) {
8184 auto [cost, node] = pq.top();
8185 pq.pop();
8186 if(vis.contains(node)) {
8187 continue;
8188 }
8189 vis.insert(node);
8190 if(node->x == m - 1 && node->y == n - 1) {
8191 return cost;
8192 }
8193 for(auto [sibling, c]: node->siblings) {
8194 if(!vis.contains(sibling)) {
8195 pq.push({cost + c, sibling});
8196 }
8197 }
8198 }
8199 return 0;
8200 }

被这些函数引用 leetcode::minimum_cost_to_make_at_least_one_valid_path_in_a_grid::TEST().


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