luogu#P16358. [BalticOI 2026] Island

    ID: 16537 远端评测题 1000ms 512MiB 尝试: 0 已通过: 0 难度: 8 上传者: 标签>图论建模最近公共祖先 LCABalticOI(波罗的海)2026

[BalticOI 2026] Island

Problem Description

You are given an n×nn\times n grid where each cell is either land or water. The rows and columns of the grid are numbered 1,2,,n1,2,\dots,n. You can move in the grid by taking steps left, right, up or down. Two cells are connected if you can move between them in one or more steps, while staying on the same type of cell.

The land cells form one connected island and the water cells form one connected ocean. The first and last rows and columns contain only water cells.

Your task is to answer qq queries: given two land cells (r1,c1)(r_1,c_1) and (r2,c2)(r_2,c_2), what is the minimum number of steps needed to move from the first cell to the second one while staying on land?

Input Format

The first line contains two integers nn and qq: the size of the grid and the number of queries.

The next nn lines each have nn characters describing the grid. "." is a water cell and "#" is a land cell.

The next qq lines each have four integers r1r_1, c1c_1, r2r_2 and c2c_2: the row and column of the first cell, followed by the row and column of the second cell.

Output Format

Print the answer to each query on separate lines.

8 4
........
..####..
.##.###.
.##.###.
.#......
.#####..
..#####.
........
2 3 3 7
4 5 4 5
4 7 7 7
6 2 3 2
5
0
17
3

Hint

Constraints

  • 3n10003\le n\le 1000
  • 1q1051\le q\le 10^5
  • 1<r1,c1,r2,c2<n1 < r_1,c_1,r_2,c_2 < n in all queries

Scoring

Subtask Constraints Points
1 n200n \le 200, q200q \le 200 1010
2 No row or column has any water cells between land cells 66
3 No 2×22\times2-squares have only land cells 1616
4 No row has any water cells between land cells 2828
5 No additional constraints 4040