주어진 규칙에 따라 시뮬레이션하는 문제입니다.

현재 위치와 방향을 관리하면서 회전을 처리하는 것이 중요하다고 생각합니다.

한편 규칙이 어느 정도 혼란을 줄 수 있게 서술되어 있는 것 같아 주의가 필요해 보입니다.

코드
use std::io::{stdin, Read};

fn main() {
    let mut input = String::new();
    stdin().read_to_string(&mut input).unwrap();
    let mut input = input.split_ascii_whitespace().map(str::parse).flatten();
    let n = input.next().unwrap();
    let m = input.next().unwrap();
    let mut r = input.next().unwrap();
    let mut c = input.next().unwrap();
    let d = input.next().unwrap();
    let mut grid = Matrix(input.take(n * m).collect(), m);
    let (mut dr, mut dc): (usize, usize) = match d {
        0 => (!0, 0),
        1 => (0, 1),
        2 => (1, 0),
        _ => (0, !0),
    };
    loop {
        grid[r][c] = 2;
        let mut found = false;
        for _ in 0..4 {
            let tmp = dr;
            dr = dc.wrapping_neg();
            dc = tmp;
            let sr = r.wrapping_add(dr);
            let sc = c.wrapping_add(dc);
            if grid[sr][sc] == 0 {
                r = sr;
                c = sc;
                found = true;
                break;
            }
        }
        if !found {
            let br = r.wrapping_sub(dr);
            let bc = c.wrapping_sub(dc);
            if grid[br][bc] == 1 {
                break;
            }
            r = br;
            c = bc;
        }
    }
    println!("{}", grid.0.iter().filter(|&&x| x == 2).count());
}

struct Matrix<T>(Vec<T>, usize);

impl<T> std::ops::Index<usize> for Matrix<T> {
    type Output = [T];
    fn index(&self, index: usize) -> &Self::Output {
        &self.0[index * self.1..][..self.1]
    }
}

impl<T> std::ops::IndexMut<usize> for Matrix<T> {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        &mut self.0[index * self.1..][..self.1]
    }
}