Created
June 23, 2020 08:14
-
-
Save misterpoloy/e4d091c08f5b9bd8a643146ac7e14eda to your computer and use it in GitHub Desktop.
#CodeChallenge Get the lenght of all the rivers, rivers are represented by 1 and land by 0
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <vector> | |
using namespace std; | |
vector<vector<int>> getUnvisitedNeighbors(int i, int j, vector<vector<int>> matrix, vector<vector<int>>& visited) { | |
vector<vector<int>> unvisitedNeighbors{}; | |
// Top | |
if (i > 0 && !visited[i - 1][j]) { | |
unvisitedNeighbors.push_back({ i - 1, j}); | |
} | |
// Bottom | |
if (i < matrix.size() - 1 && !visited[i + 1][j]) { | |
unvisitedNeighbors.push_back({ i + 1, j}); | |
} | |
// left | |
if (j > 0 && !visited[i][j - 1]) { | |
unvisitedNeighbors.push_back({ i, j - 1}); | |
} | |
// Right | |
if (j < matrix[0].size() - 1 && !visited[i][j + 1]) { | |
unvisitedNeighbors.push_back({ i, j + 1}); | |
} | |
return unvisitedNeighbors; | |
} | |
void traverseNode(int i, int j, vector<vector<int>> matrix, vector<vector<int>>* visited, vector<int>* sizes) { | |
int currentRiverSize = 0; | |
vector<vector<int>> nodesToExplore{{ i, j }}; // * We need pairs to store neighbors | |
while (nodesToExplore.size() != 0) { // Depth first search iterative | |
vector<int> currentNode = nodesToExplore.back(); | |
nodesToExplore.pop_back(); | |
int i = currentNode[0]; | |
int j = currentNode[1]; | |
// Method 1, access pointer using dereference. // Acces vector different | |
if (((*visited)[i])[j]) { // Skip if visited | |
continue; | |
} | |
visited->at(i)[j] = true; // Mark as visited | |
if (matrix[i][j] == 0) { // Skip if land | |
continue; | |
} | |
currentRiverSize += 1; // Then is river, increment. | |
// * The format is pairs, so return up to 4 possible pairs. | |
vector<vector<int>> unvisitedNeighbors = getUnvisitedNeighbors(i, j, matrix, *visited); | |
// Add all the neighbors pairs to nodes to explore queue. | |
for (vector<int> neighbor : unvisitedNeighbors) { | |
nodesToExplore.push_back(neighbor); | |
} | |
} | |
if (currentRiverSize > 0) { | |
sizes->push_back(currentRiverSize); | |
} | |
} | |
// O(wh) time | O(wh) space | |
vector<int> riverSizes(vector<vector<int>> matrix) { | |
vector<int> sizes = {}; | |
int height = matrix[0].size(); | |
vector<vector<int>> visited(matrix.size(), vector<int>(height, false)); | |
for (int i = 0; i < matrix.size(); i++) { | |
for (int j = 0; j < matrix[i].size(); j++) { | |
if (visited[i][j]) continue; | |
traverseNode(i, j, matrix, &visited, &sizes); | |
} | |
} | |
return sizes; | |
} |
Author
misterpoloy
commented
Jun 23, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment