#include <bits/stdc++.h> #include <iostream> #include <cstdio> #include <algorithm> #include <cmath> #include <cstring> #include <vector> #include <map> #include <set> #include <bitset> #include <queue> #include <deque> #include <stack> #include <iomanip> #include <cstdlib> using namespace std; #define is_lower(c) (c>='a' && c<='z') #define is_upper(c) (c>='A' && c<='Z') #define is_alpha(c) (is_lower(c) || is_upper(c)) #define is_digit(c) (c>='0' && c<='9') #define min(a,b) ((a)<(b)?(a):(b)) #define max(a,b) ((a)>(b)?(a):(b)) #define IO ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define For(i,a,b) for(int i = a; i <= b; i++) typedef long long ll; typedef unsigned long long ull; typedef pair<int,int> pii; typedef pair<ll,ll> pll; typedef vector<int> vi; const ll inf=1000000007LL; const double EPS=1e-10; const ll inf_ll=(ll)1e18; const ll maxn=100005LL; const ll mod=1000000007LL; const int MAX = 1000+5; int N,K; int mp[1000+5][1000+5]; int dp[1000+5][1000+5]; int main() { cin>>N>>K; int minn = inf; For(i,0,N-1){ minn = inf; For(j,0,K-1){ scanf("%d",&mp[i][j]); } } for(int i = N-2;i>=0;i--) { minn = inf; for(int j = 0; j <= K-1;j++) { minn==inf; for(int k = 0; k <= K-1; k++) if(minn>(mp[i][j]+mp[i+1][k])&&j!=k) minn=mp[i][j]+mp[i+1][k]; mp[i][j] = minn; } } minn = inf; For(i,0,K-1) minn = min(minn,mp[0][i]); cout<<minn<<endl; return 0; } /* 4 3 2 3 2 9 1 4 7 8 1 2 8 3 */