LeetCode 959. Regions Cut By Slashes
原题链接在这里:https://leetcode.com/problems/regions-cut-by-slashes/
题目:
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:
Input:
[
" /",
" "
]
Output: 1
Explanation: The 2x2 grid is as follows:
Example 3:
Input:
[
"\\/",
"/\\"
]
Output: 4
Explanation: (Recall that because \ characters are escaped, "\\/" refers to \/, and "/\\" refers to /\.)
The 2x2 grid is as follows:
Example 4:
Input:
[
"/\\",
"\\/"
]
Output: 5
Explanation: (Recall that because \ characters are escaped, "/\\" refers to /\, and "\\/" refers to \/.)
The 2x2 grid is as follows:
Example 5:
Input:
[
"//",
"/ "
]
Output: 3
Explanation: The 2x2 grid is as follows:
Note:
1 <= grid.length == grid[0].length <= 30
grid[i][j]
is either'/'
,'\'
, or' '
.
题解:
If one grid is divided by both '/' and '\\', then it could be 4 regions.
Mark them as 0,1,2,3 for top, right, bottom and left part.
If there is no '/', then 0 and 1 are unioned, 2 and 3 are unioned.
If there is no '\\', then 0 and 3 are unioned, 1 and2 are unioned.
For two adjacent grids, left grid part 1 and right grid part 3 are unioned. top grid part 2 and bottom grid part 0 are unioned.
Finally return unions count.
Time Complexity: O(n^2logn). n = grid.length. find takes O(log(n^2)) = O(logn). With path compression and union by weight, amatorize O(1).
Space: O(n^2).
AC Java:
1 class Solution { 2 int [] parent; 3 int [] size; 4 int count; 5 int n; 6 7 public int regionsBySlashes(String[] grid) { 8 if(grid == null || grid.length == 0){ 9 return 0; 10 } 11 12 n = grid.length; 13 parent = new int[n*n*4]; 14 size = new int[n*n*4]; 15 count = n*n*4; 16 17 for(int i = 0; i<n*n*4; i++){ 18 parent[i] = i; 19 size[i] = 1; 20 } 21 22 for(int i = 0; i<n; i++){ 23 for(int j = 0; j<n; j++){ 24 if(i > 0){ 25 union(getIndex(i-1, j, 2), getIndex(i, j, 0)); 26 } 27 28 if(j > 0){ 29 union(getIndex(i, j-1, 1), getIndex(i, j, 3)); 30 } 31 32 if(grid[i].charAt(j) != '/'){ 33 union(getIndex(i, j, 0), getIndex(i, j, 1)); 34 union(getIndex(i, j, 2), getIndex(i, j, 3)); 35 } 36 37 if(grid[i].charAt(j) != '\\'){ 38 union(getIndex(i, j, 0), getIndex(i, j, 3)); 39 union(getIndex(i, j, 1), getIndex(i, j, 2)); 40 } 41 } 42 } 43 44 return count; 45 } 46 47 private void union(int i, int j){ 48 int p = find(i); 49 int q = find(j); 50 if(p != q){ 51 if(size[p] > size[q]){ 52 parent[q] = p; 53 size[p] += size[q]; 54 }else{ 55 parent[p] = q; 56 size[q] += size[p]; 57 58 } 59 60 count--; 61 } 62 } 63 64 private int find(int i){ 65 while(i != parent[i]){ 66 parent[i] = parent[parent[i]]; 67 i = parent[i]; 68 } 69 70 return parent[i]; 71 } 72 private int getIndex(int i, int j, int k){ 73 return (i*n+j)*4+k; 74 } 75 }