summaryrefslogtreecommitdiff
path: root/2023/day17.rs
blob: 37aff454532ce842d1591041f5a79c3581ac8d82 (plain)
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
#![allow(dead_code)]
#![allow(unused_variables)]
#![allow(unused_mut)]
use num::complex::Complex as c;
use num::Complex;
use std::cmp::min;
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;

type Matrix<T> = Vec<Vec<T>>;

fn rec(
    pos: Complex<i32>,
    dir: Complex<i32>,
    conti: u32,
    mut hl: i32,
    s: &mut HashMap<(Complex<i32>, Complex<i32>, u32), i32>,
    m: &Matrix<i32>,
) -> i32 {
    if !(0 <= pos.re && pos.re < m[0].len() as i32 && 0 <= pos.im && pos.im < m.len() as i32) {
        return 999999999;
    }
    hl += m[pos.im as usize][pos.re as usize];

    if conti > 3 {
        return 999999999;
    }

    // println!("{}", pos);
    if let Some(hl_) = s.get(&(pos, dir, conti)) {
        if hl_ <= &hl {
            return 999999999;
        }
    }
    s.insert((pos, dir, conti), hl);

    if pos == c::new(m[0].len() as i32 - 1, m.len() as i32 - 1) {
        return hl;
    }

    let mut ret = 999999999;
    let new_pos = pos + dir;
    let new_dir = dir;
    ret = min(ret, rec(new_pos, new_dir, conti + 1, hl, s, m));

    let new_pos = pos + dir;
    let new_dir = dir * c::i();
    ret = min(ret, rec(new_pos, new_dir, 0, hl, s, m));

    let new_pos = pos + dir;
    let new_dir = dir * (-c::i());
    ret = min(ret, rec(new_pos, new_dir, 0, hl, s, m));

    return ret;
}

fn main() {
    let filename = "in/day17.ref";
    // let filename = "in/day17.pzl";

    let mut f = File::open(filename).expect("cannot open file");
    let mut content = String::new();
    f.read_to_string(&mut content).expect("cannot read file");
    let lines = content.trim_end().split('\n');
    // println!("{:?}", lines);

    let mut m: Matrix<i32> = Vec::new();
    for line in lines {
        let mut mr: Vec<i32> = Vec::new();
        for c in line.chars() {
            mr.push(c.to_digit(10).unwrap() as i32);
        }
        m.push(mr);
    }
    // println!("{:?}", m);

    let mut state: HashMap<(Complex<i32>, Complex<i32>, u32), i32> = HashMap::new();
    let mut pos = c::new(0, 0);
    let mut dir = c::new(1, 0);

    let res1 = rec(pos, dir, 0, 0, &mut state, &m);
    // println!("{:?}", state);

    let mut res2 = 0;

    println!("res1: {}", res1);
    println!("res2: {}", res2);
}
// 612 too low