-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathGrid Graph.cpp
67 lines (46 loc) · 1.12 KB
/
Grid Graph.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
const int N = 5e3 + 4;
// Four direction move
int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};
// Eight direction move
// int dx[8] = {0, 0, 1, 1, 1, -1, -1, -1};
// int dy[8] = {1, -1, -1, 0, 1, -1, 0, 1};
// horse move
// int dx[8] = {2, 2, -2, -2, 1, 1, -1, -1};
// int dy[8] = {1, -1, 1, -1, 2, -2, 2, -2};
int n, m;
string s[N];
bool vis[N][N];
bool isSafe(int x, int y) {
if (x >= 0 && y >= 0 && x < n && y < m && vis[x][y] == 0)
return 1;
return 0;
}
void dfs(int x, int y){
vis[x][y] = 1;
for (int i = 0; i < 4; i++){
int nx = x + dx[i];
int ny = y + dy[i];
if (isSafe(nx, ny)) {
dfs(nx, ny);
}
}
}
void bfs(int sx, int sy) {
queue<pair<int, int>> q;
q.push({sx, sy});
vis[sx][sy] = 1;
while (q.size()) {
int x = q.front().first;
int y = q.front().second;
q.pop();
for (int i = 0; i < 4; i++){
int nx = x + dx[i];
int ny = y + dy[i];
if (isSafe(nx, ny)) {
vis[nx][ny] = 1;
q.push({nx, ny});
}
}
}
}