Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit bf4ad77

Browse files
Added DFS on Grid
1 parent 69f08b0 commit bf4ad77

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

‎graph-theory/dfs_on_2d_grid.cpp‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/*
2+
***************************
3+
* *
4+
* Author: Swaraj Deep *
5+
* *
6+
***************************
7+
*/
8+
9+
#include <iostream>
10+
#include <vector>
11+
#include <queue>
12+
13+
using namespace std;
14+
15+
bool is_valid(int x, int y, vector<vector<bool>> &visited)
16+
{
17+
int n = visited.size(), m = visited[0].size();
18+
if (x < 1 || x >= n || y < 1 || y >= m || visited[x][y])
19+
{
20+
return false;
21+
}
22+
return true;
23+
}
24+
25+
vector<int> dx{-1, 0, 1, 0};
26+
vector<int> dy{0, 1, 0, -1};
27+
28+
void dfs_on_grid(int x, int y, vector<vector<bool>> &visited)
29+
{
30+
visited[x][y] = true;
31+
cout << x << ' ' << y << '\n';
32+
for (int i = 0; i < 4; ++i)
33+
{
34+
if (is_valid(x + dx[i], y + dy[i], visited))
35+
{
36+
dfs_on_grid(x + dx[i], y + dy[i], visited); // if the grid x + dx[i] and y + dy[i] is valid and not visited call dfs_on_grid
37+
}
38+
}
39+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /