This page is still under construction.

Parts of this page are still being built. What you see may change.

Linear Algebra and Applications

Time limit2sMemory limit256 MB

Summary
For a sparse n-by-n matrix A, find the least k with A plus A^2 plus ... plus A^k nonzero in every entry, or output 0 if none exists.
Level

Medium7 of 10

Topics
Graph, BFS, Matrix, Shortest path
Solved
No attempts yet

Problem

To celebrate taking a linear algebra course, Cheongung gives Hyowon an n×nn\times n matrix AA as a gift. To make it easy to work with, every entry is a nonnegative integer, and the matrix has at most 5n5n nonzero entries. In the spirit of taking linear algebra, Hyowon computes A2A^2 and finds that A+A2A+A^2 has no more zero entries than AA. Likewise, A+A2+A3A+A^2+A^3 has no more zero entries than A+A2A+A^2. Hyowon falls into this train of thought.

"Could there be some kk for which A+A2+⋯+AkA+A^2+\cdots+A^k has no zero entries at all? If such a kk exists, what is the smallest one?"

Hyowon asks Cheongung about this and receives the answer "If kk exists, then by the Cayley-Hamilton theorem it is at most nn..." For Hyowon, who is not satisfied with this answer, write a program that determines whether such a kk exists and, if it does, prints its smallest value.

Input

The first line gives the size of the matrix, nn, where 5≤n≤1,0005\leq n\leq 1,000.

The n×nn\times n matrix AA is given over the second line through the (n+1)(n+1)-th line. Each line contains nn integers separated by spaces, and the jj-th number on the (i+1)(i+1)-th line is aija_{ij}. Each entry satisfies 0≤aij≤1090\leq a_{ij}\leq 10^9, and at most 5n5n of the aija_{ij} are greater than 00.

Output

If a kk satisfying the condition exists, print the smallest such kk. If no such kk exists, print 0.

Examples2

  1. Example 1

    Input
    5
    3 1 0 0 1
    0 0 0 8 0
    2 0 1 0 1
    0 0 0 0 1
    1 5 4 0 0
    Expected output
    3
  2. Example 2

    Input
    5
    0 0 0 0 5
    0 0 0 4 0
    0 0 3 0 0
    0 2 0 0 0
    1 0 0 0 0
    Expected output
    0