import java.util.*;
public class FoxConnection3
{
{
public boolean[][] mat;
{
input = simpl(input);
mat = new boolean[input.length][input[0].length];
for(int i = 0; i < input.length; i++)
for(int j = 0; j < input[0].length; j++)
mat[i][j] = input[i][j];
}
boolean[][] simpl(boolean[][] mat)
{
int minX = mat.length, maxX = 0, minY = mat[0].length, maxY = 0;
for(int i = 0; i < mat.length; i++)
for(int j = 0; j < mat[0].length; j++)
if(mat[i][j])
{
minX
= Math.
min(minX, i
); maxX
= Math.
max(maxX, i
); minY
= Math.
min(minY, j
); maxY
= Math.
max(maxY, j
); }
boolean[][] ret = new boolean[maxX - minX + 1][maxY - minY + 1];
for(int i = minX; i <= maxX; i++)
for(int j = minY; j <= maxY; j++)
ret[i - minX][j - minY] = mat[i][j];
return ret;
}
{
for(int i = 0; i < mat.length; i++)
{
for(int j = 0; j < mat[0].length; j++)
if(mat[i][j])
ret += "1";
else
ret += "0";
ret += "\n";
}
return ret;
}
public int[] getPosition(int id)
{
int k = 0;
for(int i = 0; i < mat.length; i++)
for(int j = 0; j < mat[0].length; j++)
if(mat[i][j])
{
if(k == id)
{
int[] ret = new int[2];
ret[0] = i;
ret[1] = j;
return ret;
}
k ++;
}
return new int[2];
}
};
int k;
int[] xs, ys;
int[] p;
long ret;
long calc()
{
long ret = 0;
long[] t = new long[k];
for(int i = 0; i < k; i++)
t[i] = currentShape.getPosition(i)[0] - xs[p[i]];
for(int i = 0; i < k; i++)
ret
+= Math.
abs(t
[i
] - t
[k
/2]); for(int i = 0; i < k; i++)
t[i] = currentShape.getPosition(i)[1] - ys[p[i]];
for(int i = 0; i < k; i++)
ret
+= Math.
abs(t
[i
] - t
[k
/2]); return ret;
}
void dfs(int cur, int mask)
{
if(cur == k)
ret
= Math.
min(ret, calc
()); else
{
for(int i = 0; i < k; i++)
if(((1<<i)&mask) == 0)
{
p[cur] = i;
dfs(cur + 1, mask | (1<<i));
}
}
}
public long minimalSteps(int[] _x, int[] _y)
{
k = _x.length;
int[] dx = {1, -1, 0, 0};
int[] dy = {0, 0, 1, -1};
xs = _x;
ys = _y;
p = new int[k];
for(int i = 0; i < 9; i++)
shapes.add(new ArrayList<Shape>());
boolean[][] initShape = new boolean[1][1];
initShape[0][0] = true;
shapes.
get(1).
add(new Shape(initShape
)); mem.add(shapes.get(1).get(0).getHash());
for(int i = 1; i < k; i++)
for(int j = 0; j < shapes.get(i).size(); j++)
{
int n = shapes.get(i).get(j).mat.length + 2;
int m = shapes.get(i).get(j).mat[0].length + 2;
boolean[][] t = new boolean[n][m];
for(int x = 0; x < n; x++)
for(int y = 0; y < m; y++)
if(1 <= x && x < n-1 && 1 <= y && y < m-1)
t[x][y] = shapes.get(i).get(j).mat[x-1][y-1];
else
t[x][y] = false;
for(int x = 0; x < n; x++)
for(int y = 0; y < m; y++)
if(1 <= x && x < n-1 && 1 <= y && y < m-1 && t[x][y])
for(int dir = 0; dir < 4; dir++)
{
int nx = x + dx[dir];
int ny = y + dy[dir];
if(t[nx][ny] == false)
{
t[nx][ny] = true;
if(mem.contains(nextShape.getHash()) == false)
{
mem.add(nextShape.getHash());
shapes.get(i+1).add(nextShape);
}
t[nx][ny] = false;
}
}
}
ret = 1000000000000000000L;
for(int c = 0; c < shapes.get(k).size(); c++)
{
currentShape = shapes.get(k).get(c);
dfs(0, 0);
}
return ret;
}
}