Problem 027

Problem

Description

Matrix Path

Given an M x N matrix of integers, you are to write a program that computes a path of minimal weight from left to right across the matrix. A path starts anywhere in column 1 and consists of a sequence of steps terminating in column N. Each step consists of traveling from column I to column I + 1 in an adjacent (horizontal or diagonal) row. The first and last rows (rows 1 and M) of a matrix are considered adjacent; i.e., the matrix wraps so that it represents a horizontal cylinder.

The weight of a path is the sum of the integers in each of the N cells of the matrix that are visited.

The minimum paths through two slightly different 5 x 6 matrices are shown. The matrix values differ only in the bottom row. The path for the matrix on the right takes advantage of the adjacency between the first and last rows.

Input

The input consists of a sequence of matrix specifications. Each matrix specification consists of the row and column dimensions in that order on a line followed by M x N integers where M is the row dimension and N is the column dimension. The integers on a line will be separated from other integers by one or more spaces. Note: integers are not restricted to being positive. There will be one or more matrix specifications in an input file. Input is terminated by end-of-file. Here is an sample input:

5 6
3 4 1 2 8 6
6 1 8 2 7 4
5 9 3 9 9 5
8 4 1 3 2 6
3 7 2 8 6 4
5 6
3 4 1 2 8 6
6 1 8 2 7 4
5 9 3 9 9 5
8 4 1 3 2 6
3 7 2 1 2 3
2 2
9 10 9 10

Output

Two lines should be output for each matrix specification in the input file, the first line represents a minimal-weight path, and the second line is the cost of a minimal path. The path consists of a sequence of N integers (separated by one or more spaces) representing the rows that constitute the minimal path. If there is more than one path of minimal weight the path that is lexicographically smallest should be output. Here is an sample output:

1 2 3 4 4 5
16
1 2 1 5 4 5
11
1 1
19

Note

This is based on "11.6.4 Unidirectional TSP" in "Programming Challenges" by Skiena and Revilla.

Solution