MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / dfs

Function dfs

cpp/Graphs/count_islands.cpp:21–35  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

19}
20
21void dfs(int r, int c, std::vector<std::vector<int>>& matrix) {
22 // Mark the current land cell as visited.
23 matrix[r][c] = -1;
24 // Define direction vectors for up, down, left, and right.
25 int dirs[4][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
26 // Recursively call DFS on each neighboring land cell to continue
27 // exploring this island.
28 for (int i = 0; i < 4; i++) {
29 int nextR = r + dirs[i][0];
30 int nextC = c + dirs[i][1];
31 if (isWithinBounds(nextR, nextC, matrix) && matrix[nextR][nextC] == 1) {
32 dfs(nextR, nextC, matrix);
33 }
34 }
35}
36
37bool isWithinBounds(int r, int c, std::vector<std::vector<int>>& matrix) {
38 return r >= 0 && r < matrix.size() && c >= 0 && c < matrix[0].size();

Callers 5

countIslandsFunction · 0.70
CombinationsOfSumKMethod · 0.50
dfsMethod · 0.50
NQueensMethod · 0.50
dfsMethod · 0.50

Calls 1

isWithinBoundsFunction · 0.70

Tested by

no test coverage detected