using System; using System.Collections.Generic; using System.Text; using System.Linq; class Program { public void Proc() { Reader.IsDebug = false; int[] inp = Reader.ReadLine().Split(' ').Select(a => int.Parse(a)).ToArray(); int h = inp[0]; int w = inp[1]; this.Map = new bool[h][]; bool[][] goal = new bool[h][]; for (int i = 0; i < h; i++) { Map[i] = Reader.ReadLine().Split(' ').Select(a => a[0] == '1').ToArray(); goal[i] = new bool[w]; } this.mapKey = GetKey(this.Map); Task goalTask = new Task(goal, GetKey(goal), 0); SetDic(goalTask); if (dic.ContainsKey(mapKey)) { Console.WriteLine(dic[mapKey].Step); } else { Console.WriteLine("Impossible"); } } private void SetDic(Task t) { if (t.Key == this.mapKey) { return; } if (t.Step > 16) { return; } for (int i = 0; i < t.Map.Length; i++) { for (int j = 0; j < t.Map[0].Length; j++) { bool[][] nextMap = this.Conv(t.Map, i, j); Task nextTask = new Task(nextMap, GetKey(nextMap), t.Step + 1); if (dic.ContainsKey(nextTask.Key) && dic[nextTask.Key].Step <= nextTask.Step) { continue; } dic[nextTask.Key] = nextTask; SetDic(nextTask); } } } private Dictionary dic = new Dictionary(); private ulong mapKey; public struct Task { public bool[][] Map; public ulong Key; public int Step; public Task(bool[][] mp, ulong key, int step) { this.Map = mp; this.Key = key; this.Step = step; } } private ulong GetKey(bool[][] src) { ulong ret = 0; for (int i = 0; i < src.Length; i++) { for (int j = 0; j < src[i].Length; j++) { if (src[i][j]) { int idx = (i * src[i].Length) + j; ret += (ulong)(1<= row - 1 && i <= row + 1 && j >= col - 1 && j <= col + 1) { ret[i][j] = !src[i][j]; } else { ret[i][j] = src[i][j]; } } } return ret; } private bool[][] Map; public class Reader { public static bool IsDebug = true; private static String PlainInput = @" 4 4 0 0 0 0 0 1 1 0 0 1 1 0 0 0 0 0 "; private static System.IO.StringReader Sr = null; public static string ReadLine() { if (IsDebug) { if (Sr == null) { Sr = new System.IO.StringReader(PlainInput.Trim()); } return Sr.ReadLine(); } else { return Console.ReadLine(); } } } static void Main() { Program prg = new Program(); prg.Proc(); } }