summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorChristian Segundo2022-12-12 21:12:53 +0100
committerChristian Segundo2022-12-12 21:12:53 +0100
commitfbbd1a501bf73366d20c627d2523e372c46a201e (patch)
tree7b9857da72c46ba20126b0f5ef25dc80c90ba0d5
parent71f4d36a43c0f199274512266ecd5c39bdae407b (diff)
downloadadvent-of-zig-2022-fbbd1a501bf73366d20c627d2523e372c46a201e.tar.gz
single bfs instead of N
-rw-r--r--day_12.zig14
1 files changed, 6 insertions, 8 deletions
diff --git a/day_12.zig b/day_12.zig
index 57a69bb..c7a533e 100644
--- a/day_12.zig
+++ b/day_12.zig
@@ -28,13 +28,13 @@ fn parse_free(allocator: std.mem.Allocator, grid: [][]u8) void {
allocator.free(grid);
}
-fn bfs(allocator: std.mem.Allocator, grid: [][]const u8, start: Point, end: Point) u16 {
+fn bfs(allocator: std.mem.Allocator, grid: [][]const u8, start: []Point, end: Point) u16 {
var visited = std.AutoHashMap([2]i32, bool).init(allocator);
defer visited.deinit();
var queue = std.ArrayList(Point).init(allocator);
defer queue.deinit();
- queue.append(start) catch unreachable;
+ for (start) |p| queue.append(p) catch unreachable;
while (queue.items.len > 0) {
const point = queue.orderedRemove(0);
@@ -90,7 +90,7 @@ pub fn puzzle_1(allocator: std.mem.Allocator, input: []const u8) Result {
}
}
- return .{ .int = bfs(allocator, grid, start.?, end.?) };
+ return .{ .int = bfs(allocator, grid, &[_]Point{start.?}, end.?) };
}
pub fn puzzle_2(allocator: std.mem.Allocator, input: []const u8) Result {
@@ -98,9 +98,6 @@ pub fn puzzle_2(allocator: std.mem.Allocator, input: []const u8) Result {
defer parse_free(allocator, grid);
var start_points = std.ArrayList(Point).init(allocator);
- defer start_points.deinit();
-
- var distance = @intCast(u16, grid.len * grid[0].len);
var end: Point = undefined;
for (grid) |row, x| {
@@ -120,7 +117,8 @@ pub fn puzzle_2(allocator: std.mem.Allocator, input: []const u8) Result {
}
}
- for (start_points.items) |start| distance = std.math.min(distance, bfs(allocator, grid, start, end));
+ const p = start_points.toOwnedSlice() catch unreachable;
+ defer allocator.free(p);
- return .{ .int = distance };
+ return .{ .int = bfs(allocator, grid, p, end) };
}