MISERMAN - Wise And Miser


Jack is a wise and miser man. Always tries to save his money.

One day, he wants to go from city A to city B. Between A and B, there are N number of cities (including B and excluding A) and in each city there are M buses numbered from 1 to M. And the fare of each bus is different. Means for all N×M buses, fare (K) may be different or same. Now Jack has to go from city A to city B following these conditions:

  1. At every city, he has to change the bus.
  2. And he can switch to only those buses which have number either equal or 1 less or 1 greater to the previous.

You are to help Jack to go from A to B by spending the minimum amount of money.

N, M, K <= 100.

Input

Line 1: N M

Line 2: N×M Grid

Each row lists the fares the M busses to go form the current city to the next city.

Output

Single Line containing the minimum amount of fare that Jack has to give.

Example

Input:
5 5
1 3 1 2 6
10 2 5 4 15
10 9 6 7 1
2 7 1 5 3
8 2 6 1 9

Output:
10

Explanation

1 → 4 → 1 → 3 → 1: 10


hide comments
davidgalehouse: 2016-10-19 07:14:55

C#: Use RemoveEmptyEntries

Sumit : 2016-09-14 07:09:58

@Kumar Harsh: Thank you . your comment helped understanding the problem.

hamjosh1: 2016-09-13 19:48:20

learned something new :D

get_right_jr: 2016-06-04 20:06:36

Same as BYTESM2-Philosophers Stones
Read that problem first, that problem is much better explained
0.12 in Java Bottom-Up :D

sarangs: 2016-01-31 07:59:18

Problem statement of BYTESM2 is much better.......and there is no need for similar questions on spoj

dokz: 2016-01-19 07:04:03

Had Runtime error, because input contains redundant spaces. Do not use Split(' '), C# and Java developers.

devilcoder: 2015-11-21 18:39:42

copy of http://www.spoj.com/problems/BYTESM2/

r0bo_dart: 2015-06-26 11:07:00

The term changing bus every city got me confused, but then i reread it. AC at a go :D Hint: Look into the comments below for the 2 letter word :P

skywinder: 2015-06-08 03:35:21


1) At every city, he has to change the bus.
2) And he can switch to only those buses which have number either equal..

is there 2 statements is incompatible? Not clear - is it possible to go with the same bus? According example - he can stay with the same bus. but what about "he has to change the bus. "?

Last edit: 2015-06-08 03:50:03
Madhur Bhargava: 2014-11-24 04:38:56

Java Guys, please do NOT assume there are single space(s) between numbers in individual rows. String.split(" ") fails in this case, Use Stringtokenizer instead.


Added by:The quick brown fox jumps over the lazy dog
Date:2010-10-18
Time limit:1s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: ASM64 NODEJS OBJC VB.NET
Resource:Udit Agarwal