Two Weights

Given an undirected graph with two weights per edge, find the path from 0 to 1 minimizing the product of the two total weight sums.

Medium7Shortest pathGraphDynamic programmingGreedyInterviewNo attempts yetTime limit2sMemory limit512 MB

Problem

A graph GG has NN vertices numbered from 0 to N1N-1.

Every edge of GG carries two weights, called weight 1 and weight 2.

The cost of a path is W1×W2W_1 \times W_2, where W1W_1 is the sum of the weight 1 values of the edges on the path and W2W_2 is the sum of their weight 2 values. Write a program that finds the cheapest path from vertex 0 to vertex 1.

Input

The first line contains the number of vertices NN. (2N202 \le N \le 20)

The next NN lines describe weight 1, and the NN lines after that describe weight 2. Each line is a string of length NN.

Within a block, character jj of line ii is the weight of the edge between vertex ii and vertex jj. It is a digit from 1 to 9, or .. A . means there is no edge between those two vertices. Lines and characters are both counted from 0.

Write weight1 for the weight 1 block and weight2 for the weight 2 block. The input satisfies:

  • weight1[i][i] = weight2[i][i] = .
  • weight1[i][j] = weight1[j][i]
  • weight2[i][j] = weight2[j][i]
  • if weight1[i][j] is . then weight2[i][j] is ., and the converse holds as well

Output

Print the minimum cost of a path from vertex 0 to vertex 1 on the first line. If vertex 1 cannot be reached from vertex 0, print -1.