Skip to content

Commit 8670873

Browse files
committed
feat: Solve leetcode/leetcoding_challenge/2025/jan2025/week3/number_of_good_leaf_nodes_pairs.cpp
1 parent 088e713 commit 8670873

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
#include <algorithm>
2+
#include <vector>
3+
#include <queue>
4+
#include <set>
5+
#include <limits>
6+
#include <map>
7+
#include <unordered_set>
8+
#include <unordered_map>
9+
#include <iterator>
10+
#include <sstream>
11+
#include <iostream> // includes cin to read from stdin and cout to write to stdout
12+
using namespace std; // since cin and cout are both in namespace std, this saves some text
13+
14+
class Solution {
15+
public:
16+
int minCost(vector<vector<int>>& grid) {
17+
auto HEIGHT = grid.size();
18+
// TODO: validate HEIGHT > 0
19+
auto WIDTH = grid[0].size();
20+
21+
auto START_Y = 0;
22+
auto START_X = 0;
23+
auto START_COST = 0;
24+
auto TARGET_Y = HEIGHT - 1;
25+
auto TARGET_X = WIDTH - 1;
26+
27+
auto UNINITIALZED = numeric_limits<int>::max() / 2;
28+
29+
vector<pair<int, int>> DIRECTIONS = {
30+
{0, 1}, // right
31+
{0, -1}, // left
32+
{1, 0}, // low
33+
{-1, 0}, // up
34+
};
35+
36+
vector<vector<int>> best(HEIGHT, vector<int>(WIDTH, UNINITIALZED));
37+
best[START_Y][START_X] = START_COST;
38+
39+
priority_queue<tuple<int, int, int>> pq;
40+
pq.push(tuple(-START_COST, START_Y, START_X));
41+
42+
while (pq.size() > 0) {
43+
auto [negCost, y, x] = pq.top();
44+
pq.pop();
45+
auto cost = -negCost;
46+
if (y == TARGET_Y && x == TARGET_X) {
47+
return cost;
48+
}
49+
50+
for (auto i = 0; i < DIRECTIONS.size(); ++i) {
51+
auto gridValue = i + 1;
52+
auto [dy, dx] = DIRECTIONS[i];
53+
auto ny = y + dy;
54+
auto nx = x + dx;
55+
bool isWithinBoundary = 0 <= ny && ny < HEIGHT && 0 <= nx && nx < WIDTH;
56+
if (!isWithinBoundary) {
57+
continue;
58+
}
59+
auto nCost = gridValue == grid[y][x] ? cost : (cost + 1);
60+
if (nCost >= best[ny][nx]) {
61+
continue;
62+
}
63+
best[ny][nx] = nCost;
64+
pq.push(tuple(-nCost, ny, nx));
65+
}
66+
}
67+
68+
// TODO: or throw error here - programing error
69+
// return best[HEIGHT - 1][WIDTH - 1];
70+
return -1;
71+
}
72+
};

0 commit comments

Comments
 (0)