According to the purple Book of ideas, from the final state of the push back, each time is derived from three directions, take out the minimum value in three directions and the current value to combine and record the corresponding number. The final output can be, the specific implementation see the following code:
#include <iostream>
#include <vector>
#include <string>
#include <set>
#include <stack>
#include <queue>
#include <map>
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <cstring>
#include <sstream>
#include <cstdio>
#include <deque>
using namespace std;
int m, n;
int data [15] [110];
int ind [15] [110];
int ans [15] [110];
int main () {
while (cin >> m >> n) {
memset (ind, -1, sizeof (ind));
memset (ans, 0, sizeof (ans));
for (int i = 0; i <m; i ++) {
for (int j = 0; j <n; j ++) {
cin >> data [i] [j];
}
}
for (int j = n-1; j> = 0; j-) {// col
for (int i = 0; i <m; i ++) {
int row [3] = {i, i-1, i + 1};
if (row [1] <0) row [1] = m-1;
if (row [2]> = m) row [2] = 0;
sort (row, row + 3);
ans [i] [j] = 1 << 20;
for (int k = 0; k <3; k ++) {
int temp = ans [row [k]] [j + 1] + data [i] [j];
if (temp <ans [i] [j]) {
ans [i] [j] = temp;
if (j! = n-1) ind [i] [j] = row [k];
}
}
}
}
int start;
int temp = 1 << 20;
for (int i = 0; i <m; i ++) {
if (ans [i] [0] <temp) {
temp = ans [i] [0];
start = i;
}
}
cout << start + 1;
int j = 0;
while (ind [start] [j]! = -1) {
cout << "" << ind [start] [j] +1;
start = ind [start] [j];
j ++;
}
cout << endl;
cout << temp << endl;
}
return 0;
}