Problem:
Score : 400 points

Problem Statement

Consider a grid with H rows and W columns of squares. Let (r, c) denote the square at the r-th row from the top and the c-th column from the left.
Each square is painted black or white.

The grid is said to be good if and only if the following condition is satisfied:

From (1, 1), we can reach (H, W) by moving one square right or down repeatedly, while always being on a white square.

Note that (1, 1) and (H, W) must be white if the grid is good.

Your task is to make the grid good by repeating the operation below. Find the minimum number of operations needed to complete the task. It can be proved that you can always complete the task in a finite number of operations.

Choose four integers r_0, c_0, r_1, c_1(1 \leq r_0 \leq r_1 \leq H, 1 \leq c_0 \leq c_1 \leq W). For each pair r, c (r_0 \leq r \leq r_1, c_0 \leq c \leq c_1), invert the color of (r, c) - that is, from white to black and vice versa.

Constraints

2 \leq H, W \leq 100

Input

Input is given from Standard Input in the following format:

H W
s_{11} s_{12} \cdots s_{1W}
s_{21} s_{22} \cdots s_{2W}
\vdots
s_{H1} s_{H2} \cdots s_{HW}

Here s_{rc} represents the color of (r, c) - # stands for black, and . stands for white.

Output

Print the minimum number of operations needed.

Sample Input 1

3 3
.##
.#.
##.

Sample Output 1

1

Do the operation with (r_0, c_0, r_1, c_1) = (2, 2, 2, 2) to change just the color of (2, 2), and we are done.

Sample Input 2

2 2
#.
.#

Sample Output 2

2

Sample Input 3

4 4
..##
#...
###.
###.

Sample Output 3

0

No operation may be needed.

Sample Input 4

5 5
.#.#.
#.#.#
.#.#.
#.#.#
.#.#.

Sample Output 4

4

Solution in C# (Mono 4.6.2.0) (judge verdict: Wrong Answer)

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Numerics;

namespace CompetitionPrograming2
{
    public sealed class Program : BaseProgram
    {
        public static void Main(string[] _) { using (new SetConsole()) { Solve(); } }
        public static void Solve()
        {
            var hw = GetArray<int>();
            var h = hw[0];
            var w = hw[1];
            var map = new char[h][];
            for (int i = 0; i < h; i++)
            {
                map[i] = GetString().AsEnumerable().ToArray();
            }

            // 始点から行ける白ますの距離
            var costsfromStart = Bfs(map, new int[] { 0, 0 }, h, w);
            if (costsfromStart.Any(x => x.Item1[0] == 0 && x.Item1[1] == 0)
                && costsfromStart.Any(x => x.Item1[0] == h - 1 && x.Item1[1] == w - 1))
            {
                Write(0); return;
            }


            // 終点から行ける白ますの距離
            var costsfromGoal = Bfs2(map, new int[] { h - 1, w - 1 }, h, w);

            var minCost = int.MaxValue;
            foreach (var fromStart in costsfromStart)
            {
                var fromStartPos = fromStart.Item1;
                var fromStartCost = fromStart.Item2;
                foreach (var fromGoal in costsfromGoal)
                {
                    var fromGoalPos = fromGoal.Item1;
                    var fromGoalCost = fromGoal.Item2;
                    if (fromStartPos[0] > fromGoalPos[0]) { continue; }

                    if (fromStartPos[1] > fromGoalPos[1]) { continue; }

                    var distanse = fromGoalPos[0] - fromStartPos[0] + fromGoalPos[1] - fromStartPos[1] - 1;
                    var decrease1 = 0;
                    {
                        if (fromStartPos[0] != 0 || fromStartPos[1] != 0)
                        {
                            if (map[0][0] == '#')
                            {
                                decrease1++;
                            }
                        }
                        if (fromGoalPos[0] != h - 1 || fromGoalPos[1] != w - 1)
                        {
                            if (map[h - 1][w - 1] == '#')
                            {
                                decrease1++;
                            }
                        }
                        for (int i = fromStartPos[0]; i <= fromGoalPos[0]; i++)
                        {
                            if (map[i][fromStartPos[1]] == '#')
                            {
                                decrease1++;
                            }
                        }
                        for (int i = fromStartPos[1]; i <= fromGoalPos[1]; i++)
                        {
                            if (map[fromGoalPos[0]][i] == '#')
                            {
                                decrease1++;
                            }
                        }
                    }
                    var decrease2 = 0;
                    {
                        if (fromStartPos[0] != 0 || fromStartPos[1] != 0)
                        {
                            if (map[0][0] == '#')
                            {
                                decrease2++;
                            }
                        }
                        if (fromGoalPos[0] != h - 1 || fromGoalPos[1] != w - 1)
                        {
                            if (map[h - 1][w - 1] == '#')
                            {
                                decrease2++;
                            }
                        }
                        for (int i = fromStartPos[1]; i <= fromGoalPos[1]; i++)
                        {
                            if (map[fromStartPos[0]][i] == '#')
                            {
                                decrease2++;
                            }
                        }
                        for (int i = fromStartPos[0]; i <= fromGoalPos[0]; i++)
                        {
                            if (map[i][fromGoalPos[1]] == '#')
                            {
                                decrease2++;
                            }
                        }
                    }

                    minCost = Math.Min(minCost, Math.Min(decrease1, decrease2));
                }
            }

            Write(minCost);
        }

        private static List<Tuple<int[], int>> Bfs(char[][] map, int[] start, int h, int w)
        {
            var costs = new int[h][];
            for (int i = 0; i < h; i++)
            {
                costs[i] = Enumerable.Repeat(int.MaxValue, w).ToArray();
            }
            costs[start[0]][start[1]] = 0;
            var que = new Queue<Tuple<int[], int>>();
            que.Enqueue(Tuple.Create(start, 0));
            while (que.Any())
            {
                var current = que.Dequeue();
                var pos = current.Item1;
                var cost = current.Item2;

                {
                    var right = new int[] { pos[0], pos[1] + 1 };
                    if (w > right[1] && map[right[0]][right[1]] == '.' && cost + 1 < costs[right[0]][right[1]])
                    {
                        costs[right[0]][right[1]] = cost + 1;
                        que.Enqueue(Tuple.Create(right, cost + 1));
                    }
                }

                var down = new int[] { pos[0] + 1, pos[1] };
                if (h > down[0] && map[down[0]][down[1]] == '.' && cost + 1 < costs[down[0]][down[1]])
                {
                    costs[down[0]][down[1]] = cost + 1;
                    que.Enqueue(Tuple.Create(down, cost + 1));
                }
            }

            var result = new List<Tuple<int[], int>>();
            for (int i = 0; i < h; i++)
            {
                for (int j = 0; j < w; j++)
                {
                    if (costs[i][j] == int.MaxValue) { continue; }

                    result.Add(Tuple.Create(new int[] { i, j }, costs[i][j]));
                }
            }
            return result;
        }

        private static List<Tuple<int[], int>> Bfs2(char[][] map, int[] start, int h, int w)
        {
            var costs = new int[h][];
            for (int i = 0; i < h; i++)
            {
                costs[i] = Enumerable.Repeat(int.MaxValue, w).ToArray();
            }
            costs[start[0]][start[1]] = 0;
            var que = new Queue<Tuple<int[], int>>();
            que.Enqueue(Tuple.Create(start, 0));
            while (que.Any())
            {
                var current = que.Dequeue();
                var pos = current.Item1;
                var cost = current.Item2;

                {
                    var left = new int[] { pos[0], pos[1] - 1 };
                    if (0 < left[1] && map[left[0]][left[1]] == '.' && cost + 1 < costs[left[0]][left[1]])
                    {
                        costs[left[0]][left[1]] = cost + 1;
                        que.Enqueue(Tuple.Create(left, cost + 1));
                    }
                }

                var up = new int[] { pos[0] - 1, pos[1] };
                if (0 < up[0] && map[up[0]][up[1]] == '.' && cost + 1 < costs[up[0]][up[1]])
                {
                    costs[up[0]][up[1]] = cost + 1;
                    que.Enqueue(Tuple.Create(up, cost + 1));
                }
            }

            var result = new List<Tuple<int[], int>>();
            for (int i = 0; i < h; i++)
            {
                for (int j = 0; j < w; j++)
                {
                    if (costs[i][j] == int.MaxValue) { continue; }

                    result.Add(Tuple.Create(new int[] { i, j }, costs[i][j]));
                }
            }
            return result;
        }
    }
    public abstract class BaseProgram
    {
        protected readonly static long divisor = 1000000007;
        protected static Action<object> Write => Console.WriteLine;
        protected static string GetString()
        {
            var str = Console.ReadLine();
            if (str == null) { throw new NullReferenceException("標準入力がnullです Solveメソッド内の解答コードが間違っています"); }
            return str;
        }
        protected static T GetNumber<T>() where T : IComparable, IComparable<T>, IConvertible, IEquatable<T>, IFormattable
        {
            var str = GetString();
            var t = typeof(T);
            try
            {
                if (t == typeof(int))
                {
                    return (T)(object)str.ToInt();
                }
                else if (t == typeof(long))
                {
                    return (T)(object)str.ToLong();
                }
                else if (t == typeof(double))
                {
                    return (T)(object)str.ToDouble();
                }
                else if (t == typeof(decimal))
                {
                    return (T)(object)str.ToDecimal();
                }
                else if (t == typeof(BigInteger))
                {
                    return (T)(object)str.ToBigInteger();
                }
            }
            catch (OverflowException)
            {
                throw new OverflowException("より大きい数値型を指定してください");
            }
            throw new NotSupportedException();
        }
        protected static T[] GetArray<T>() where T : IComparable, IComparable<T>, IConvertible, IEquatable<T> => ToArray<T>(GetString());
        protected static List<T> GetList<T>() where T : IComparable, IComparable<T>, IConvertible, IEquatable<T> => ToList<T>(GetString());
        protected static void Swap<T>(ref T item1, ref T item2)
        {
            var tmp = item1;
            item1 = item2;
            item2 = tmp;
        }
        protected static IEnumerable<char> AtoZ()
        {
            for (char i = 'a'; i <= 'z'; i++)
            {
                yield return i;
            }
        }
        private static T[] ToArray<T>(string str) where T : IComparable, IComparable<T>, IConvertible, IEquatable<T>
        {
            return ConvertEnumerator<T>(str).ToArray();
        }
        private static List<T> ToList<T>(string str) where T : IComparable, IComparable<T>, IConvertible, IEquatable<T>
        {
            if (typeof(T) == typeof(string)) { return (List<T>)(object)str.Split().ToList(); }

            return ConvertEnumerator<T>(str).ToList();
        }
        private static IEnumerable<T> ConvertEnumerator<T>(string str) where T : IComparable, IComparable<T>, IConvertible, IEquatable<T>
        {
            var t = typeof(T);
            if (t == typeof(byte))
            {
                return str.Split().Select(byte.Parse).Cast<T>();
            }
            if (t == typeof(int))
            {
                return str.Split().Select(int.Parse).Cast<T>();
            }
            if (t == typeof(long))
            {
                return str.Split().Select(long.Parse).Cast<T>();
            }
            if (t == typeof(double))
            {
                return str.Split().Select(double.Parse).Cast<T>();
            }
            if (t == typeof(decimal))
            {
                return str.Split().Select(decimal.Parse).Cast<T>();
            }
            if (t == typeof(BigInteger))
            {
                return str.Split().Select(BigInteger.Parse).Cast<T>();
            }
            throw new NotSupportedException();
        }
        protected sealed class SetConsole : IDisposable
        {
            readonly StreamWriter sw = new StreamWriter(Console.OpenStandardOutput());
            public SetConsole()
            {
                sw.AutoFlush = false;
                Console.SetOut(sw);
            }
            public void Dispose()
            {
                Console.Out.Flush();
                sw.AutoFlush = true;
                Console.SetOut(sw);
            }
        }
    }
    public static class ExtentionsLibrary
    {
        public static long Combination(this long num, long m)
        {
            if (num == m) { return 1; }
            if (m == 0) { return 1; }
            BigInteger ans = 1;
            var tmpM = m;
            while (tmpM > 0)
            {
                ans *= num;
                num--;
                tmpM--;
            }
            while (m > 0)
            {
                ans /= m;
                m--;
            }
            return (long)ans;
        }
        /// <summary>
        /// 階乗を求める
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        public static long Factorial(this long num)
        {
            var result = 1L;
            for (int i = 1; i <= num; i++)
            {
                result *= i;
            }
            return result;
        }
        public static T[] NextPermutation<T>(this IEnumerable<T> collection) where T : IComparable
        {
            var array = collection.ToArray();
            int? exchangingNumIndex = null;
            for (int i = 1; i < array.Length; i++)
            {
                if (array[i - 1].CompareTo(array[i]) >= 0) { continue; }

                exchangingNumIndex = i - 1;
            }

            if (exchangingNumIndex == null) { return null; }

            for (int j = array.Length - 1; j >= 0; j--)
            {
                if (array[(int)exchangingNumIndex].CompareTo(array[j]) >= 0) { continue; }

                var tmp = array[j];
                array[j] = array[(int)exchangingNumIndex];
                array[(int)exchangingNumIndex] = tmp;
                array = array.Take((int)exchangingNumIndex + 1).Concat(array.Skip((int)exchangingNumIndex + 1).Reverse()).ToArray();
                break;
            }
            return array;
        }
        public static IEnumerable<T[]> Permutations<T>(this IEnumerable<T> collection) where T : IComparable
        {
            var next = collection.NextPermutation();

            while (next != null)
            {
                yield return next;

                next = next.NextPermutation();
            }
        }
        public static long Gcd(this long a, long b)
        {
            if (a < b) { return Gcd(b, a); }
            long tmp;
            do
            {
                tmp = a % b;
                a = b;
                b = tmp;
            } while (tmp != 0);
            return a;
        }
        /// <summary>
        /// 素因数分解を行う
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        public static IEnumerable<Tuple<long, int>> Factorize(this long n)
        {
            yield return Tuple.Create(1L, 1);
            var rootN = Math.Sqrt(n);
            for (long i = 2; i <= rootN; i++)
            {
                if (n % i != 0) { continue; }

                var count = 1;
                n /= i;
                while (n % i == 0)
                {
                    n /= i;
                    count++;
                }
                yield return Tuple.Create(i, count);
            }
            if (n != 1) { yield return Tuple.Create(n, 1); }
        }
        public static int ToInt(this string str) => int.Parse(str);
        public static int ToInt(this char chr) => int.Parse(chr.ToString());
        public static long ToLong(this string str) => long.Parse(str);
        public static double ToDouble(this string str) => double.Parse(str);
        public static decimal ToDecimal(this string str) => decimal.Parse(str);
        public static BigInteger ToBigInteger(this string str) => BigInteger.Parse(str);
        public static DateTime ToDateTime(this string str) => DateTime.Parse(str);
        public static string StringJoin<T>(this IEnumerable<T> collection, string separator = "") => string.Join(separator, collection.Select(c => c.ToString()));
        public static string StringConcat(this IEnumerable<char> collection) => string.Concat(collection);
        public static int LowerBound<T>(this IReadOnlyList<T> a, T v) => LowerBound(a, v, Comparer<T>.Default);
        public static int LowerBound<T>(this IReadOnlyList<T> a, T v, Comparer<T> cmp)
        {
            var l = 0;
            var r = a.Count - 1;
            while (l <= r)
            {
                var mid = l + (r - l) / 2;
                var result = cmp.Compare(a[mid], v);
                if (result == -1)
                {
                    l = mid + 1;
                }
                else
                {
                    r = mid - 1;
                }
            }
            return l;
        }
        public static int UpperBound<T>(this IReadOnlyList<T> a, T v) => UpperBound(a, v, Comparer<T>.Default);
        public static int UpperBound<T>(this IReadOnlyList<T> a, T v, Comparer<T> cmp)
        {
            var l = 0;
            var r = a.Count - 1;
            while (l <= r)
            {
                var mid = l + (r - l) / 2;
                var res = cmp.Compare(a[mid], v);
                if (res <= 0) l = mid + 1;
                else r = mid - 1;
            }
            return l;
        }
    }

    public struct Mint
    {
        private static readonly long MOD = (long)1e9 + 7;

        /// <summary>
        /// 0以上MOD未満の整数
        /// </summary>
        public long Value;

        public Mint(long val)
        {
            Value = val % MOD;
            if (Value < 0) Value += MOD;
        }

        private static Mint Ctor(long val) => new Mint() { Value = val };
        public static Mint operator +(Mint a, Mint b)
        {
            long res = a.Value + b.Value;
            if (res > MOD) res -= MOD;
            return Ctor(res);
        }
        public static Mint operator -(Mint a, Mint b)
        {
            long res = a.Value - b.Value;
            if (res < 0) res += MOD;
            return Ctor(res);
        }
        public static Mint operator *(Mint a, Mint b)
        {
            long res = a.Value * b.Value;
            if (res > MOD) res %= MOD;
            return Ctor(res);
        }
        public static Mint operator /(Mint a, Mint b) => a * Inv(b);
        public static Mint Pow(Mint a, long n)
        {
            if (n == 0) return new Mint(1);
            Mint b = Pow(a, n >> 1);
            b *= b;
            if ((n & 1) == 1) b *= a;
            return b;
        }
        public static Mint Inv(Mint n)
        {
            long a = n.Value;
            long b = MOD;

            long x = 1;
            long u = 0;
            while (b != 0)
            {
                long k = a / b;
                long _x = u;
                u = x - k * u;
                x = _x;

                long _a = a;
                a = b;
                b = _a - (k * b);
            }

            return new Mint(x);
        }
        public override string ToString() => Value.ToString();
        public static implicit operator Mint(long a) => new Mint(a);
        public static explicit operator long(Mint a) => a.Value;
        public static Mint Choose(long n, long k)
        {
            Mint numerator = 1, denominator = 1;
            for (int i = 0; i < k; i++)
            {
                numerator *= n - i;
                denominator *= i + 1;
            }
            return numerator / denominator;
        }
    }
    public enum Priority : byte
    {
        Smaller = 0,
        Larger = 1
    }
}