Problem:
Score: 400 points

Problem statement

We have an H \times W grid whose squares are painted black or white. The square at the i-th row from the top and the j-th column from the left is denoted as (i, j).

Snuke would like to play the following game on this grid. At the beginning of the game, there is a character called Kenus at square (1, 1). The player repeatedly moves Kenus up, down, left or right by one square. The game is completed when Kenus reaches square (H, W) passing only white squares.

Before Snuke starts the game, he can change the color of some of the white squares to black. However, he cannot change the color of square (1, 1) and (H, W). Also, changes of color must all be carried out before the beginning of the game.

When the game is completed, Snuke's score will be the number of times he changed the color of a square before the beginning of the game. Find the maximum possible score that Snuke can achieve, or print -1 if the game cannot be completed, that is, Kenus can never reach square (H, W) regardless of how Snuke changes the color of the squares.

The color of the squares are given to you as characters s_{i, j}. If square (i, j) is initially painted by white, s_{i, j} is .; if square (i, j) is initially painted by black, s_{i, j} is #.

Constraints

H is an integer between 2 and 50 (inclusive).

W is an integer between 2 and 50 (inclusive).

s_{i, j} is . or # (1 \leq i \leq H, 1 \leq j \leq W).

s_{1, 1} and s_{H, W} are ..

Input

Input is given from Standard Input in the following format:

H W
s_{1, 1}s_{1, 2}s_{1, 3} ... s_{1, W}
s_{2, 1}s_{2, 2}s_{2, 3} ... s_{2, W}
: :
s_{H, 1}s_{H, 2}s_{H, 3} ... s_{H, W}

Output

Print the maximum possible score that Snuke can achieve, or print -1 if the game cannot be completed.

Sample Input 1

3 3
..#
#..
...

Sample Output 1

2

The score 2 can be achieved by changing the color of squares as follows:

Sample Input 2

10 37
.....................................
...#...####...####..###...###...###..
..#.#..#...#.##....#...#.#...#.#...#.
..#.#..#...#.#.....#...#.#...#.#...#.
.#...#.#..##.#.....#...#.#.###.#.###.
.#####.####..#.....#...#..##....##...
.#...#.#...#.#.....#...#.#...#.#...#.
.#...#.#...#.##....#...#.#...#.#...#.
.#...#.####...####..###...###...###..
.....................................

Sample Output 2

209

Solution in Rust (1.15.1) (judge verdict: Wrong Answer)

use std::io;
use std::str::FromStr;

fn main() {
    let hw = reads(&get_line());
    let mut cells = vec![];
    for _ in 0..hw[1] {
        cells.extend(get_line().trim().chars().map(|x| Cell::from_char(&x)));
    }
    let mut f = Field {
        cells: cells,
        size: (hw[1], hw[0]),
    };
    let c = f.search();
    let ans = c.map(|cost| f.size.0 * f.size.1 - 1 - f.walls() - cost as usize);
    match ans {
        Some(n) => println!("{}", n),
        None => println!("-1"),
    }
}

#[derive(Debug)]
struct Field {
    cells: Vec<Cell>,
    size: (usize, usize),
}

impl Field {
    fn at_mut(&mut self, loc: &usize) -> &mut Cell {
        &mut self.cells[*loc]
    }
    fn search(&mut self) -> Option<u32> {
        let mut paths: Vec<usize> = vec![0];
        let mut cost = 0;
        loop {
            let mut paths_n = vec![];
            if paths.is_empty() {
                return None;
            }
            for &path in &paths {
                if self.at_mut(&path).arrive(cost).is_some() {
                    if path == self.size.0 * self.size.1 - 1 {
                        // reached the goal
                        return Some(cost);
                    }
                    paths_n.extend(&self.neighbours(path));
                }
            }
            cost += 1;
            paths = paths_n;
        }
    }

    fn report(&self) -> () {
        for (i, cell) in self.cells.iter().enumerate() {
            let cha = match *cell {
                Cell::Path { cost: Some(x) } => format!("{:>4}", x),
                Cell::Path { cost: None } => "....".to_string(),
                Cell::Wall => "####".to_string(),
            };
            print!("{}", cha);
            if (i + 1) % self.size.0 == 0 {
                print!("\n");
            }
        }
    }

    //     fn step(&mut self, paths: &[usize], cost: u32) -> Option<u32> {
    //         if paths.is_empty() {
    //             return None;
    //         }
    //         let mut path_n = vec![];
    //         None
    //     }

    fn neighbours(&self, c: usize) -> Vec<usize> {
        // need more succinct expressions
        return (vec![]);
        let w = self.size.0 as i32;
        let h = self.size.1 as i32;
        let (x, y) = (c as i32 % w, c as i32 / w);
        let mut nbs = vec![];
        for &(p, q) in &[(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)] {
            if 0 <= p && p < w && 0 <= q && q < h {
                nbs.push((p + w * q) as usize);
            }
        }
        nbs
    }

    fn walls(&self) -> usize {
        self.cells
            .iter()
            .filter(|&c| match *c {
                Cell::Wall => true,
                _ => false,
            })
            .count()
    }
}

#[derive(Debug)]
enum Cell {
    Path { cost: Option<u32> },
    Wall,
}

impl Cell {
    fn from_char(c: &char) -> Self {
        match *c {
            '.' => Cell::Path { cost: None },
            '#' => Cell::Wall,
            _ => panic!("else"),
        }
    }
    fn arrive(&mut self, cost: u32) -> Option<u32> {
        match *self {
            Cell::Path { cost: ref mut c } => {
                // TODO:understand
                match *c {
                    None => {
                        *c = Some(cost);
                        Some(cost)
                    }
                    Some(_) => None,
                }
            }
            _ => None,
        }
    }
}

fn get_line() -> String {
    let mut inp = String::new();
    io::stdin().read_line(&mut inp).expect("read error");
    inp.trim().to_string()
}

fn reads<T>(input: &str) -> Vec<T>
where
    T: FromStr,
    T::Err: std::fmt::Debug,
{
    input
        .trim()
        .split_whitespace()
        .map(|n| n.parse().unwrap())
        .collect()
}