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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
|
fn small(s: &str) -> bool {
s.bytes().all(|c| c.is_ascii_lowercase())
}
fn single_small<'a>(path: impl Iterator<Item = &'a str>) -> bool {
let mut set = std::collections::HashSet::new();
for s in path {
if !small(s) {
continue;
}
if set.contains(s) {
return false;
}
set.insert(s);
}
true
}
fn paths_from1<'a>(
graph: &'a std::collections::HashMap<
String,
std::collections::HashSet<String>,
>,
path: &mut Vec<&'a str>,
) -> i64 {
let mut total = 0;
for neighbor in graph[path[path.len() - 1]].iter() {
if small(neighbor) && path.contains(&neighbor.as_ref()) {
continue;
}
if neighbor == "end" {
total += 1;
} else {
path.push(neighbor);
total += paths_from1(graph, path);
path.pop();
}
}
total
}
fn paths_from2<'a>(
graph: &'a std::collections::HashMap<
String,
std::collections::HashSet<String>,
>,
path: &mut Vec<&'a str>,
) -> i64 {
let mut total = 0;
for neighbor in graph[path[path.len() - 1]].iter() {
if neighbor == "start" {
continue;
}
if small(neighbor)
&& path.contains(&neighbor.as_ref())
&& !single_small(path.iter().copied())
{
continue;
}
if neighbor == "end" {
total += 1;
} else {
path.push(neighbor);
total += paths_from2(graph, path);
path.pop();
}
}
total
}
pub fn parse(
fh: std::fs::File,
) -> anyhow::Result<
std::collections::HashMap<String, std::collections::HashSet<String>>,
> {
let mut graph = std::collections::HashMap::new();
for line in crate::util::parse::lines(fh) {
let nodes: Vec<String> =
line.split('-').map(|s| s.to_string()).collect();
let edges = graph
.entry(nodes[0].clone())
.or_insert_with(std::collections::HashSet::new);
edges.insert(nodes[1].clone());
let edges = graph
.entry(nodes[1].clone())
.or_insert_with(std::collections::HashSet::new);
edges.insert(nodes[0].clone());
}
Ok(graph)
}
pub fn part1(
graph: std::collections::HashMap<
String,
std::collections::HashSet<String>,
>,
) -> anyhow::Result<i64> {
Ok(paths_from1(&graph, &mut vec!["start"]))
}
pub fn part2(
graph: std::collections::HashMap<
String,
std::collections::HashSet<String>,
>,
) -> anyhow::Result<i64> {
Ok(paths_from2(&graph, &mut vec!["start"]))
}
#[test]
fn test() {
assert_eq!(
part1(parse(crate::util::data(2021, 12).unwrap()).unwrap()).unwrap(),
3230
);
assert_eq!(
part2(parse(crate::util::data(2021, 12).unwrap()).unwrap()).unwrap(),
83475
);
}
|