#include <iostream>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
#define MAXN 10
#define INF 987654321
int dist[7][7];
int num_bridge = 0;
int map[MAXN][MAXN];
bool visited[MAXN][MAXN];
vector<bool> seleted;
struct node {
int u;
int v;
int weights;
};
vector<node> adj;
int ans = INF;
int N, M;
int dx[] = { 0,0,1,-1 };
int dy[] = { 1,-1,0,0 };
bool is_range(int x, int y) {
return (x >= 0 && y >= 0 && x < N && y < M);
}
void get_num(int x, int y) {
visited[x][y] = true;
map[x][y] = num_bridge;
for (int k = 0; k < 4; k++) {
int nx = x + dx[k];
int ny = y + dy[k];
if (!is_range(nx, ny)) continue;
if (visited[nx][ny] || !map[nx][ny]) continue;
get_num(nx, ny);
}
}
void create_bridge(int idx) {
queue<pair<int, int> > q;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (map[i][j] == idx) {
q.push({ i,j });
}
}
}
while (!q.empty()) {
int x = q.front().first;
int y = q.front().second;
q.pop();
for (int k = 0; k < 4; k++) {
int nx = x + dx[k];
int ny = y + dy[k];
if (!is_range(nx, ny)) continue;
if (map[nx][ny]) continue;
int len = 0;
while (1) {
if (!is_range(nx, ny)) break;
if (map[nx][ny]) {
if (len >= 2 && dist[idx][map[nx][ny]] > len) {
dist[idx][map[nx][ny]] = len;
dist[map[nx][ny]][idx] = len;
}
break;
}
nx += dx[k];
ny += dy[k];
len++;
}
}
}
}
bool check() {
vector<vector<bool> > bridge(num_bridge+1, vector<bool>(num_bridge+1, false));
vector<bool> used(num_bridge+1, false);
queue<int> q;
for (int i = 0; i < adj.size(); i++) {
if (seleted[i]) {
if (q.empty()) {
q.push(adj[i].u);
used[adj[i].u] = true;
}
bridge[adj[i].u][adj[i].v] = true;
bridge[adj[i].v][adj[i].u] = true;
}
}
int cnt = 1;
while (!q.empty()) {
int cur = q.front();
q.pop();
for (int i = 1; i <= num_bridge; i++) {
if (dist[cur][i] == INF) continue;
if (!used[i] && bridge[cur][i]) {
used[i] = true;
cnt++;
q.push(i);
}
}
}
return cnt == num_bridge;
}
void connect_bridge(int cur, int w, int cnt) {
if (cnt > num_bridge) return;
if (cnt >= num_bridge - 1) {
if (check()) {
if (ans > w) ans = w;
return;
}
}
for (int i = cur; i < adj.size(); i++) {
if (seleted[i]) continue;
seleted[i] = true;
connect_bridge(i, w + adj[i].weights,cnt+1);
seleted[i] = false;
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> N >> M;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
cin >> map[i][j];
}
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (map[i][j] && !visited[i][j]) {
num_bridge++;
get_num(i, j);
}
}
}
for (int i = 1; i <= num_bridge; i++) {
for (int j = 1; j <= num_bridge; j++) {
dist[i][j] = INF;
}
}
for (int i = 1; i <= num_bridge; i++) {
create_bridge(i);
}
for (int i = 1; i <= num_bridge; i++) {
for (int j = i + 1; j <= num_bridge; j++) {
if (dist[i][j] == INF)continue;
adj.push_back({ i,j,dist[i][j] });
}
}
seleted = vector<bool>(adj.size(),false);
connect_bridge(0,0,0);
if (ans == INF)cout << "-1\n";
else cout << ans << "\n";
return 0;
}