#!/usr/bin/env python3 # @EXPECTED_RESULTS@: ACCEPTED,TIME_LIMIT_EXCEEDED h, w = map(int, input().split()) plots = [list(map(int, input().split())) for _ in range(h)] def find_paths(dest_x, dest_y, dest): seen, stack = [[0] * w for _ in range(h)], [(dest_x, dest_y, 0)] while stack: x, y, dist = stack.pop() # Move from (x, y) to neighbour (xx, yy) if (x, y) is the closest plot number from (xx, yy) for xx, yy in ((x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)): if 0 <= xx < w and 0 <= yy < h and not seen[yy][xx] and min( (abs(neigh - dest), abs(neigh - plots[yy][xx]), x3, y3) for x3, y3, neigh in ((x2, y2, plots[y2][x2]) for x2, y2 in ((xx - 1, yy), (xx + 1, yy), (xx, yy - 1), (xx, yy + 1)) if 0 <= x2 < w and 0 <= y2 < h))[2:] == (x, y): stack.append((xx, yy, dist + 1)) seen[yy][xx] = dist + 1 return seen paths = [[find_paths(x, y, plots[y][x]) for x in range(w)] for y in range(h)] best = min((max(paths[dest_y][dest_x][kiosk_y][kiosk_x] or 1e9 for dest_y in range(h) for dest_x in range(w)), plots[kiosk_y][kiosk_x]) for kiosk_y in range(h) for kiosk_x in range(w)) print("impossible") if best[0] == 1e9 else print(*best[::-1])