-
Notifications
You must be signed in to change notification settings - Fork 0
/
BFS 2D.cpp
42 lines (40 loc) · 841 Bytes
/
BFS 2D.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <bits/stdc++.h>
using namespace std;
int vis[N][N], dist[N][N], ways[N][N];
int dx[4] = {-1, +1, 0, 0};
int dy[4] = {0, 0, +1, -1};
void bfs(int x, int y, int n, int m)
{
queue<pair<int, int>> q;
q.push({x, y});
ways[x][y] = 1;
vis[x][y] = 1;
dist[x][y] = 0;
while (!q.empty())
{
int x = q.front().first;
int y = q.front().second;
q.pop();
for (int dir = 0; dir < 4; dir++)
{
int nx = x + dx[dir];
int ny = y + dy[dir];
if (nx < 1 || ny < 1 || nx > n || ny > m)
continue;
if (!vis[nx][ny])
{
dist[nx][ny] = dist[x][y] + 1;
vis[nx][ny] = 1;
ways[nx][ny] += ways[x][y];
q.push({nx, ny});
}
else
{
if (dist[x][y] + 1 == dist[nx][ny])
ways[nx][ny] += ways[x][y];
}
}
}
}
//Problem 1: https://www.spoj.com/problems/CLEANRBT/
//Solution 1: http://p.ip.fi/2fxO