Regions Cut By Slashes

update Dec 23, 19:47

LeetCodearrow-up-right

In a N x N grid composed of 1 x 1 squares, each 1 x 1 square consists of a /, \, or blank space. These characters divide the square into contiguous regions.

(Note that backslash characters are escaped, so a \ is represented as "\\".)

Return the number of regions.

Example 1:

Input:
[
" /",
"/ "
]
Output: 2
Explanation: The 2x2 grid is as follows:

Example 2:

Example 3:

Example 4:

Example 5:

Note:

  1. 1 <= grid.length == grid[0].length <= 30

  2. grid[i][j] is either '/', '\', or ' '.

Basic Idea:

这道题乍一看很新颖,但本质其实是number of islands。我们可以将一个最小的正方形看成左右上下四个三角形组成的。于是我们可以利用union find的解法,对于 ' ',我们union所有的四个三角,对于 '/',我们分别 union 左上和右下,对于 '\\',我们分别union 左下和右上 。同时因为相邻两个正方形之间的两个三角形一定是共用的,我们也需要做union。

Java Code:

DFS Solution

DFS 的解法基本思路使用像素格子将输入的图形画出来,然后dfs找联通块的数量。

Last updated