Created
January 20, 2018 18:22
-
-
Save jianminchen/f796b94821a1c13d70b37bdce9c52e73 to your computer and use it in GitHub Desktop.
Breadth first search - count connected elements - peer code using C++
This file contains 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 <iostream> | |
#include <vector> | |
#include <queue> | |
using namespace std; | |
struct vec2i { | |
int x, y; | |
}; | |
void bfs(vector<vector<int>>& binaryMatrix, int rows, int cols, vec2i pos) { | |
deque<vec2i> q; | |
q.push_back(pos); | |
while (!q.empty()) { | |
vec2i cur = q.front(); | |
q.pop_front(); | |
if (cur.x >= 0 && cur.x < rows && cur.y >= 0 && cur.y < cols) { | |
int& value = binaryMatrix[cur.x][cur.y]; | |
if (value == 1) { | |
value = 0; | |
// Add neighbours: | |
q.push_back(vec2i{cur.x - 1, cur.y}); // Left | |
q.push_back(vec2i{cur.x + 1, cur.y}); // Right | |
q.push_back(vec2i{cur.x, cur.y - 1}); // Top | |
q.push_back(vec2i{cur.x, cur.y + 1}); // Top | |
} | |
} | |
} | |
} | |
int getNumberOfIslands( const vector<vector<int>>& binaryMatrix ) | |
{ | |
auto binaryMatrixMutable = binaryMatrix; | |
int num_islands = 0; | |
int rows = binaryMatrix.size(); | |
int cols = (rows ? binaryMatrixMutable[0].size() : 0); | |
for (int row = 0; row < rows; ++row) { | |
for (int col = 0; col < cols; ++col) { | |
int value = binaryMatrixMutable[row][col]; | |
if (value == 1) { | |
bfs(binaryMatrixMutable, rows, cols, vec2i{row, col}); | |
++num_islands; | |
} | |
} | |
} | |
return num_islands; | |
} | |
int main() { | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ask the peer about C++ using struct, instead of using array
void f(int arr[256]) {
cerr << "Size of the parameter: " << sizeof(arr) << "\n";
} // empty array will return size of 8.
int main() {
f(nullptr);
return 0;
}