#include #include #include #include using namespace std; const int maxn = 1005; const int INF = 0x3f3f3f3f; int a[maxn][maxn], dp[maxn][maxn]; int n, m; bool legal(int x, int y) { return x >= 1 && y >= 1; } bool legal2(int x, int y) { return (x >= 1 && y >= 1) || (x == 0 && y == 0) || (x == 1 && y == 0) || (x == 0 && y == 1); } int main() { //freopen("in.txt", "r", stdin); while(~scanf("%d%d", &n, &m)) { for(int i = 1; i <= n; i++) { for(int j = 1; j <= m; j++) { scanf("%d", &a[i][j]); dp[i][j] = INF; } } for(int i = 1; i <= n; i++) { for(int j = 1; j <= m; j++) { if((i + j) & 1) { if(legal(i, j - 1) && legal2(i, j - 2)) dp[i][j] = min(dp[i][j], dp[i][j - 2] + a[i][j - 1] * a[i][j]); if(legal(i, j - 1) && legal2(i - 1, j - 1)) dp[i][j] = min(dp[i][j], dp[i - 1][j - 1] + a[i][j - 1] * a[i][j]); if(legal(i - 1, j) && legal2(i - 2, j)) dp[i][j] = min(dp[i][j], dp[i - 2][j] + a[i - 1][j] * a[i][j]); if(legal(i - 1, j) && legal2(i - 1, j - 1)) dp[i][j] = min(dp[i][j], dp[i - 1][j - 1] + a[i - 1][j] * a[i][j]); } } } printf("%d\n", dp[n][m]); } return 0; }