import java.io.*; import java.util.*; import java.util.stream.*; 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[][][] matrix = new long[40][m][m]; for (int i = 0; i < m; i++) { for (int j = 0; j < m; j++) { matrix[0][i][j] = sc.nextInt(); } } for (int i = 1; i < 40; i++) { for (int a = 0; a < m; a++) { for (int b = 0; b < m; b++) { for (int c = 0; c < m; c++) { matrix[i][b][c] = Math.max(matrix[i][b][c], matrix[i - 1][b][a] + matrix[i - 1][a][c]); } } } } long[] ans = new long[m]; for (int i = 39; i >= 0; i--) { if (n < (1L << i)) { continue; } n -= (1L << i); long[] next = new long[m]; for (int a = 0; a < m; a++) { for (int b = 0; b < m; b++) { next[b] = Math.max(next[b], ans[a] + matrix[i][a][b]); } } ans = next; } long result = 0; for (long x : ans) { result = Math.max(result, x); } System.out.println(result); } } class Utilities { static String arrayToLineString(Object[] arr) { return Arrays.stream(arr).map(x -> x.toString()).collect(Collectors.joining("\n")); } static String arrayToLineString(int[] arr) { return String.join("\n", Arrays.stream(arr).mapToObj(String::valueOf).toArray(String[]::new)); } } class Scanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); StringBuilder sb = new StringBuilder(); 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 int[] nextIntArray() throws Exception { return Stream.of(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); } public String next() throws Exception { while (!st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } }