import sys import itertools def solve(): W, H, hsWH, hsHW = read_data() hsWH = list(itertools.accumulate(hsWH)) hsHW = list(itertools.accumulate(hsHW)) result = wfs(W, H, hsWH, hsHW) return result def read_data(): W, H, N = map(int, input().split()) hsWH = [0] * (W * H) # vertical lines hsHW = [0] * (W * H) # horizontal lines lines = sys.stdin.readlines() flag = True for line in lines: flag = not flag if flag: Bs = list(map(int, line.split())) h0, w0 = divmod(Bs[0], W) for b in Bs: h1, w1 = divmod(b, W) if h0 == h1: # horizontal move if w0 > w1: hsHW[b] += 1 hsHW[b + w0 - w1] -= 1 else: hsHW[b + w0 - w1] += 1 hsHW[b] -= 1 w0 = w1 else: # vertical move if h0 > h1: hsWH[w1 * H + h1] += 1 hsWH[w1 * H + h0] -= 1 else: hsWH[w1 * H + h0] += 1 hsWH[w1 * H + h1] -= 1 h0 = h1 return W, H, hsWH, hsHW def wfs(W, H, hsWH, hsHW): ''' (0, 0) から (W-1, H-1) までの最短距離を求める。 hsWH[w * H + h]: cell(w, h) と cell(w, h+1) に辺があるか否か hsHW[h * W + w]: cell(w, h) と cell(w+1, h) に辺があるか否か ''' start = 0 goal = H * W - 1 unvisited = [True] * (H * W) frontiers = [start] cost = 0 while frontiers: cost += 1 new_frontiers = [] for f in frontiers: if f == goal: return cost - 1 g = (f % W) * H + (f//W) if hsWH[g] and unvisited[f + W]: unvisited[f + W] = False new_frontiers.append(f + W) if hsWH[g - 1] and unvisited[f - W]: unvisited[f - W] = False new_frontiers.append(f - W) if hsHW[f] and unvisited[f + 1]: unvisited[f + 1] = False new_frontiers.append(f + 1) if hsHW[f - 1] and unvisited[f - 1]: unvisited[f - 1] = False new_frontiers.append(f - 1) frontiers = new_frontiers return -1 ans = solve() if ans == -1: print("Odekakedekinai..") else: print(ans)