Created
January 20, 2018 18:34
-
-
Save jianminchen/fb2c12037dd314280d47ac668ba89d16 to your computer and use it in GitHub Desktop.
Connected component in a matrix - using dfs
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}); // Down | |
} | |
} | |
} | |
} | |
void dfs(vector<vector<int>>& binaryMatrix, int rows, int cols, vec2i pos) { | |
stack<vec2i> q; | |
q.push(pos); | |
while (!q.empty()) { | |
vec2i cur = q.top(); | |
q.pop(); | |
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(vec2i{cur.x - 1, cur.y}); // Left | |
q.push(vec2i{cur.x + 1, cur.y}); // Right | |
q.push(vec2i{cur.x, cur.y - 1}); // Top | |
q.push(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) { | |
dfs(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