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 f87d6d7

Browse files
bfs_2d_grid
1 parent e2dd122 commit f87d6d7

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

‎graph-theory/bfs_on_2d_grid.cpp‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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+
// Function to check whether cell[x][y] is valid or not
16+
bool is_valid(int x, int y, vector<vector<bool>> &visited)
17+
{
18+
int n = visited.size(), m = visited.size();
19+
if (x < 1 || x >= n || y < 1 || y >= m || visited[x][y])
20+
{
21+
return false;
22+
}
23+
return true;
24+
}
25+
26+
// Considering only adjacent cells as edges. Can also be extended for all eight cells
27+
vector<int> dx{-1, 0, 1, 0};
28+
vector<int> dy{0, 1, 0, -1};
29+
30+
void bfs_on_grid(int source_x, int source_y, vector<vector<bool>> &visited, vector<vector<int>> &distance)
31+
{
32+
queue<pair<int, int>> q;
33+
q.push({source_x, source_y}); // Inserting into the queue the current cell
34+
visited[source_x][source_y] = true;
35+
distance[source_x][source_y] = 0; // Distance of source_x and source_y is zero
36+
while (!q.empty())
37+
{
38+
int current_x = q.front().first;
39+
int current_y = q.front().second;
40+
q.pop();
41+
// Checking all adjacent sides
42+
for (int i = 0; i < 4; ++i)
43+
{
44+
if (is_valid(current_x + dx[i], current_y + dy[i], visited))
45+
{
46+
int new_x = current_x + dx[i];
47+
int new_y = current_y + dy[i];
48+
distance[new_x][new_y] = distance[current_x][current_y] + 1;
49+
visited[new_x][new_y] = true;
50+
q.push({new_x, new_y});
51+
}
52+
}
53+
}
54+
}

0 commit comments

Comments
(0)

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