1462 Puzzle
Description
cryboy likes puzzles a lot! Just a few days ago, he found out about the NM puzzle. For this puzzle, you have all the numbers from 0 to NM-1 arranged in n rows and m columns. You are allowed to switch two adjacent elements (horizontally or vertically), only if one of them has the value 0. For example, the 4x5 puzzle, the following state is a possible state of the puzzle:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 0
Given the initial state and the final state of the puzzle, you have to decide whether there exists a sequence of moves which brings the puzzle in the initial state into the final state.
Input:
The input contains multiple test cases, each case will be formatted in the following description:
The first line contains two numbers: N, M(2≤N, M≤50).
The following N lines, each of them contains M integers, describing the initial state of the puzzle.
The next N lines, each of them contains M integers, describing the final state of the puzzle.
Output:
For each case, you should print "YES" if the final state can be reached after several moves or "NO", if such a thing is impossible.
Sample
Input
4 4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 0
1 2 3 4
5 6 7 8
9 10 11 0
13 14 15 12
2 3
1 2 3
4 5 0
1 2 0
4 3 5
Output
YES
NO
Source: cryboy
Comments