問題一覧 > 通常問題

No.124 Kadomatsu Sequence (3)

レベル : / AI推定難易度 : 1025 / 実行時間制限 : 1ケース 5.000秒 / メモリ制限 : 512 MB / 標準ジャッジ問題
タグ : (AC するまで非表示) / 解いたユーザー数 131
作問者 : yuki2006
お気に入りにしたユーザー ProblemId : 222 / 自分の提出
問題文最終更新日: 2026-06-25 07:20:08
This statement was translated by AI (claude-opus-5-5, effort medium) and may contain errors or differ in nuance from the original. The original statement takes precedence. Back to the original
yukicoder contest 75 (順位表) の他の問題:

Problem Statement

In the previous "trends and countermeasures for Kadomatsu sequences" problem, the Kadomatsu sequence problem I had been planning to set was guessed, so it seemed all was lost, but instead we have ended up leaving one-dimensional sequences and jumping out onto a two-dimensional grid.

As has appeared many times recently, a "Kadomatsu sequence" is one that satisfies the conditions "the second largest of the lengths of the 3 bamboo stalks is on the left or right side" and "all 3 lengths are different".

Here, you are given a $W\times H$ planar grid in which each cell has a number from $1$ to $9$ written on it.
On these cells, you can move from your current position by 1 cell up, down, left, or right (Manhattan distance 1) per step.
However, the numbers of the 2 most recently visited places and the new cell must, in that order, form a Kadomatsu sequence.

In other words, let $A$ be the history of the numbers of the cells reached, with $A_i$ being the number of the $i$-th cell passed through, and
let $isKadomatsuSequence$ be a function that determines whether a sequence is a Kadomatsu sequence. Then,

$isKadomatsuSequence(A_{i−2},A_{i-1},A_{i})$
must be true for all $i\ge 3$ along the path.
(Up to the first 2 steps, there are not 3 values yet, so the Kadomatsu condition need not hold.)

With the top-left $(1,1)$ as the start and the bottom-right $(W,H)$ as the goal,
output the minimum number of steps needed to reach the goal.
If the goal cannot be reached under these conditions, output -1.

Input

$W$ $H$
$M_{1,1}\ M_{2,1} \dots M_{W,1}$
$M_{1,2}\ M_{2,2} \dots M_{W,2}$
$\dots\dots\dots\dots\dots\dots$
$M_{1,H}\ M_{2,H} \dots M_{W,H}$

All input values are integers.
$2\le W \le 100=10^2$
$2\le H \le 100=10^2$
$1\le M_{i,j}\le 9$
$1\le i \le W,1\le j \le H$

Output

Find the minimum number of steps needed to reach the goal from the start.
If the goal cannot be reached under these conditions, output -1.
Print a newline at the end.

Sample

Sample 1
Input
3 3
1 2 3
3 2 1
1 4 1
Output
4

By moving along $[1,3,2,4,1]$,
$[1,3,2]$,$[3,2,4]$,$[2,4,1]$ are each Kadomatsu sequences. The answer can also be described as the number of Kadomatsu sequences + 1.

Sample 2
Input
2 2
1 3
2 2
Output
2

The goal is reached with just one Kadomatsu sequence.

Sample 3
Input
4 4
1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7
Output
-1

In this case, the goal cannot be reached.

Sample 4
Input
3 3
5 4 1
6 6 9
2 8 8
Output
6

提出するには、Twitter 、GitHub、 Googleもしくは右上の雲マークをクリックしてアカウントを作成してください。