2048 (Easy)

Time limit1sMemory limit512 MB

Summary
Find the largest tile reachable within at most five 2048 moves on a given board where no new tiles appear.
Level

Medium5 of 10

Topics
Brute force, Backtracking, Simulation
Solved
No attempts yet

Problem

2048 is a single player puzzle game played on a 4×44 \times 4 board.

One move pushes every block on the board in one of the four directions: up, down, left, or right. When two blocks of equal value collide, they merge into a single block whose value is twice as large. Within one move, a block that has already merged does not merge again during that same move. The original game adds a new block after every move, but in this problem no new block ever appears.

Figure 1Figure 2Figure 3
Figure 1Figure 2Figure 3

Moving the blocks up from Figure 1 gives Figure 2. Moving them left from there gives Figure 3.

Figure 4Figure 5Figure 6Figure 7
Figure 4Figure 5Figure 6Figure 7

Moving the blocks right from Figure 4 gives Figure 5, and moving them up from there gives Figure 6. Moving them right from Figure 6 gives Figure 7.

Figure 8Figure 9
Figure 8Figure 9

Moving the blocks left from Figure 8 makes the two 2 blocks collide and merge into a 4, which gives Figure 9.

Figure 10Figure 11Figure 12Figure 13
Figure 10Figure 11Figure 12Figure 13

Moving the blocks up from Figure 10 gives Figure 11. Moving them up from Figure 12 gives Figure 13, because a block that has already merged during a move does not merge again in that move.

Figure 14Figure 15
Figure 14Figure 15

When three blocks of equal value sit in a row, the two blocks nearer the direction of the move merge first. For a move upward, the upper two blocks merge. Moving up from Figure 14 gives Figure 15.

The 2048 game in this problem is played on a board of size N×NN \times N. Given the board size and the initial arrangement of the blocks, write a program that finds the largest block value obtainable with at most 5 moves.

Input

The first line contains the board size NN. (1≤N≤201 \le N \le 20)

Each of the next NN lines contains NN values describing the initial board. A 0 is an empty cell and any other value is a block. The number written on a block is a power of two between 2 and 1024, inclusive. At least one block is present.

Output

Print the largest block value obtainable with at most 5 moves. Making no move at all is allowed, so the answer is never smaller than the largest block on the initial board.

Examples1

  1. Example 1

    Input
    3
    2 2 2
    4 4 4
    8 8 8
    
    Expected output
    16