import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(); long n = sc.nextLong() - 1; int m = sc.nextInt(); long[][][] dp = new long[33][m][m]; for (int i = 0; i < m; i++) { for (int j = 0; j < m; j++) { dp[0][i][j] = sc.nextInt(); } } for (int i = 1; i < 33; i++) { for (int j = 0; j < m; j++) { for (int k = 0; k < m; k++) { for (int l = 0; l < m; l++) { dp[i][j][k] = Math.max(dp[i][j][k], dp[i - 1][j][l] + dp[i - 1][l][k]); } } } } long[][] current = new long[m][m]; for (int i = 32; i >= 0; i--) { if (n < (1L << i)) { continue; } n -= (1L << i); long[][] next = new long[m][m]; for (int j = 0; j < m; j++) { for (int k = 0; k < m; k++) { for (int l = 0; l < m; l++) { next[j][k] = Math.max(next[j][k], current[j][l] + dp[i][l][k]); } } } current = next; } long max = 0; for (long[] arr : current) { for (long x : arr) { max = Math.max(max, x); } } System.out.println(max); } } class Scanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public Scanner() throws Exception { } public int nextInt() throws Exception { return Integer.parseInt(next()); } public long nextLong() throws Exception { return Long.parseLong(next()); } public double nextDouble() throws Exception { return Double.parseDouble(next()); } public String nextLine() throws Exception { return br.readLine(); } public String next() throws Exception { if (!st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } }