Under construction

Still being built. Things may change

Chisam's Stepping Stone Crossing

Time limit1sMemory limit1024 MB

Summary
Water spreads from given sources one cell per day; find the earliest day Chisam can walk over watered stones from (1,1) to (N,N).
Level

Medium7 of 10

Topics
BFS, Binary search, Graph, Array
Solved
No attempts yet

Problem

Chisam wants to cross a square valley that is NN wide and NN tall. But the tremendous heat has dried up all the water!

The valley consists of ground and stones. The whole ground is made of 1×11\times1 cells, and a cell may contain a stone. The ground and stones in the valley are too hot to walk on. However, a cell with a stone becomes cool enough to walk on once water flows into it. Fortunately, kind students dug into the ground to create water sources for Chisam, and Chisam decided to cross the valley by stepping on stones. A water source may lie on either ground or a stone. Water spreads once a day from each cell that contains water to cells adjacent to it. Diagonal cells are not considered adjacent.

Chisam wants to travel from the starting point (1,1)(1, 1) to the destination (N,N)(N, N). Stones always lie at the starting point (1,1)(1, 1) and the destination (N,N)(N, N), and Chisam can walk on them without meeting water. Chisam's movement takes no time. Chisam can move up, down, left, right, and diagonally. Find the number of days it takes for Chisam to reach the destination (N,N)(N, N) as fast as possible.

Input

The first line gives the size of the ground N(3≤N≤1,000)N(3 \le N \le 1,000) and the number of water sources W(1≤W≤N)W(1 \le W \le N).

Lines 2 through W+1W+1 give the position of each water source xx (row), yy (column) (1≤x,y≤N)(1 \le x, y \le N).

From line W+2W+2, NN lines give the map of the stream. 1 marks a cell with a stone, and 0 marks a cell with ground.

NN, WW, xx, and yy are all positive integers.

Output

Print the number of days it takes to reach the destination as fast as possible. If Chisam cannot reach the destination (N,N)(N, N), print -1.

Examples2

  1. Example 1

    Input
    3 1
    1 1
    101
    101
    011
    
    Expected output
    3
    
  2. Example 2

    Input
    6 3
    5 4
    1 6
    6 4
    110111
    110011
    011000
    001010
    111101
    111001
    
    Expected output
    5