All problems

Problem 621

Count Sub Islands

Medium · 20 pts · Matrix, Depth-First Search, Union Find

Problem

You are given two binary grids GRID1 and GRID2 of the same size, where 1 is land and 0 is water. An island is a group of land cells connected horizontally or vertically. An island of GRID2 is a sub-island if every one of its cells is also land in GRID1. Count the sub-islands of GRID2. Explore each island of GRID2 with a flood fill, and mark it as failed if any of its cells is water in GRID1.

Input

The first line contains R and C. The next R lines are the rows of GRID1, and the R lines after them are the rows of GRID2, each a string of C characters 0 or 1.

Output

Print the number of sub-islands.

Constraints

1 <= R, C <= 500

Example input

5 5
11100
01111
00000
10000
11011
11100
00111
01000
10110
01010

Example output

3

Explanation

GRID2 has five islands here. Two of them include a cell that is water in GRID1, so they do not count, and the other three lie completely on GRID1 land. The answer is 3.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Number of Ways to Reorder Array to Get Same BST Next: Making a Large Island