Skip to content

Commit acc0cfb

Browse files
Merge pull request #239 from admirerr/main
feat(graph): added maximal network rank and jump game 3 in cpp
2 parents d1f33da + ece3e1b commit acc0cfb

2 files changed

Lines changed: 88 additions & 0 deletions

File tree

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#include <iostream>
2+
#include <vector>
3+
using namespace std;
4+
5+
class Solution {
6+
public:
7+
bool canReach(vector<int>& nums, int startIndex) {
8+
vector<int> visited(nums.size(), 0);
9+
return explore(nums, startIndex, visited);
10+
}
11+
12+
private:
13+
bool explore(vector<int>& nums, int currentIndex, vector<int>& visited) {
14+
if (currentIndex < 0 || currentIndex >= nums.size()) return false;
15+
if (visited[currentIndex]) return false;
16+
if (nums[currentIndex] == 0) return true;
17+
18+
visited[currentIndex] = 1;
19+
20+
return explore(nums, currentIndex + nums[currentIndex], visited) ||
21+
explore(nums, currentIndex - nums[currentIndex], visited);
22+
}
23+
};
24+
25+
int main() {
26+
Solution solution;
27+
28+
vector<int> nums = {4, 2, 3, 0, 3, 1, 2};
29+
int startIndex = 5;
30+
31+
bool result = solution.canReach(nums, startIndex);
32+
cout << (result ? "Reachable" : "Not Reachable") << endl;
33+
34+
return 0;
35+
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <algorithm>
4+
using namespace std;
5+
6+
class Solution {
7+
public:
8+
int maximalNetworkRank(int numCities, vector<vector<int>>& roads) {
9+
vector<int> degree(numCities, 0);
10+
vector<vector<int>> adjacency(numCities);
11+
int maxRank = 0;
12+
13+
for (int i = 0; i < roads.size(); i++) {
14+
int cityA = roads[i][0];
15+
int cityB = roads[i][1];
16+
17+
adjacency[cityA].push_back(cityB);
18+
adjacency[cityB].push_back(cityA);
19+
20+
degree[cityA]++;
21+
degree[cityB]++;
22+
}
23+
24+
for (int cityA = 0; cityA < numCities; cityA++) {
25+
for (int cityB = cityA + 1; cityB < numCities; cityB++) {
26+
int rank = degree[cityA] + degree[cityB];
27+
if (count(adjacency[cityA].begin(), adjacency[cityA].end(), cityB)) {
28+
rank--;
29+
}
30+
maxRank = max(maxRank, rank);
31+
}
32+
}
33+
34+
return maxRank;
35+
}
36+
};
37+
38+
int main() {
39+
Solution solution;
40+
41+
int numCities = 4;
42+
vector<vector<int>> roads = {
43+
{0, 1},
44+
{0, 3},
45+
{1, 2},
46+
{1, 3}
47+
};
48+
49+
int result = solution.maximalNetworkRank(numCities, roads);
50+
cout << "Maximal Network Rank: " << result << endl;
51+
52+
return 0;
53+
}

0 commit comments

Comments
 (0)