#P9904. [COCI 2023/2024 #1] Labirint

[COCI 2023/2024 #1] Labirint

Background

Teo and the Croatian EJOI team are inside a maze.

Problem Description

The maze is an n×mn \times m grid. The top-left cell is (1,1)(1,1), and the bottom-right cell is (n,m)(n,m). Between every pair of adjacent cells (4-neighborhood, i.e., adjacent up, down, left, right), there is a door. Doors have four colors: blue, red, green, and orange, represented by the characters P, C, Z, N, respectively. You can only move to other cells by passing through doors.

Now Teo gives you qq queries. Each query provides a,b,c,da,b,c,d, asking you to find a path from (a,b)(a,b) to (c,d)(c,d) that minimizes the number of distinct door colors used along the path. You need to output this minimum number of colors.

Input Format

The first line contains two integers n,mn, m, representing the number of rows and columns of the grid.

Next is a character matrix with nn rows and m1m - 1 columns. The character in row ii, column jj represents the color of the door between (i,j)(i,j) and (i,j+1)(i,j+1).

Next is a character matrix with n1n - 1 rows and mm columns. The character in row ii, column jj represents the color of the door between (i,j)(i,j) and (i+1,j)(i+1,j).

Next is one line with an integer qq, representing the number of queries.

Then follow qq lines. The ii-th line contains four integers ai,bi,ci,dia_i, b_i, c_i, d_i, meaning the minimum number of distinct door colors on a path from (ai,bi)(a_i,b_i) to (ci,di)(c_i,d_i).

Output Format

Output qq lines, each containing one integer, which is the answer to the corresponding query.

1 8
CPZNCCP
4
1 1 1 8
1 3 1 5
1 8 1 4
1 2 1 3
4
2
3
1
3 3
PP
PP
PP
CCC
CCC
3
1 1 3 3
3 3 2 2
1 1 1 3
2
2
1
4 4
CCC
CPC
PPP
CNP
ZZZZ
PPPP
CPZC
4
3 1 2 3
1 1 4 4
2 2 3 3
1 4 4 1
1
2
1
3

Hint

Sample Explanation #3

As shown in the figure.

  • For the first query, you only need to pass through blue doors.
  • For the second query, you only need to pass through blue and green doors.
  • For the third query, you only need to pass through blue doors.
  • For the fourth query, following the path in the figure, you only need to pass through red, blue, and green doors.

Constraints

For 100%100\% of the testdata, 1n,m,q1001 \le n,m,q \le 100, nm>1nm > 1, 1ai,cin1 \le a_i,c_i \le n, 1bi,dim1 \le b_i,d_i \le m, (ai,bi)(ci,di)(a_i,b_i) \ne (c_i,d_i), and the character matrices consist only of the characters P, C, Z, N.

This problem uses bundled tests.

Subtask Special Property Points
11 n=1n = 1 1111
22 The first character matrix contains only P, and the second character matrix contains only C 1313
33 All character matrices contain only C and P 2424
44 No special properties 2222

Notes

The scoring of this problem follows the original COCI problem settings, with a full score of 7070.

Translated from COCI2023-2024 CONTEST #1 T2 Labirint.

Translated by ChatGPT 5