-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolver.cs
More file actions
80 lines (58 loc) · 2.21 KB
/
solver.cs
File metadata and controls
80 lines (58 loc) · 2.21 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
using System.Collections.Generic;
using System;
class Solver {
//choose solver algorithm
//get solution from solver algorithm
public enum Profile {DFS, BFS, Unknown};
public (int x, int y)[] result;
public Solver(Maze maze, Profile choice) {
result = choice switch {
Profile.DFS => depth_first_search(maze),
Profile.BFS => breadth_first_search(maze),
_ => throw new Exception("Please choose from either dfs or bfs")
};
}
(int x, int y)[] depth_first_search(Maze maze) {
var start = maze.start;
var end = maze.end;
int width = maze.cols, height = maze.rows;
Stack<(int x, int y)> stack = new Stack<(int x, int y)>();
(int x, int y)[] path = new (int x, int y)[width * height];
bool[,] visited = new bool[width , height];
stack.Push(start);
while (stack.Count > 0) {
var curr = stack.Pop();
if (curr == end) break;
visited[curr.x, curr.y] = true;
foreach (var neighbor in maze.get_adjacent(curr, visited)) {
if (neighbor != (0,0)) {
stack.Push(neighbor);
path[neighbor.x + neighbor.y * width] = curr;
}
}
}
return path;
}
(int x, int y)[] breadth_first_search(Maze maze) {
var start = maze.start;
var end = maze.end;
int width = maze.cols, height = maze.rows;
Queue<(int x, int y)> queue = new Queue<(int x, int y)>();
(int x, int y)[] path = new (int x, int y)[width * height];
bool[,] visited = new bool[width , height];
visited[start.x, start.y] = true;
queue.Enqueue(start);
while (queue.Count > 0) {
var curr = queue.Dequeue();
if (curr == end) break;
foreach (var neighbor in maze.get_adjacent(curr, visited)) {
if (neighbor != (0,0)) {
queue.Enqueue(neighbor);
visited[neighbor.x, neighbor.y] = true;
path[neighbor.x + neighbor.y * width] = curr;
}
}
}
return path;
}
}