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:
1 2 3 4 5 6 7
Input: [ " /", "/ " ] Output: 2 Explanation: The 2x2 grid is as follows:
Example 2:
1 2 3 4 5 6 7
Input: [ " /", " " ] Output: 1 Explanation: The 2x2 grid is as follows:
Example 3:
1 2 3 4 5 6 7 8
Input: [ "\\/", "/\\" ] Output: 4 Explanation: (Recall that because \ characters are escaped, "\\/" refers to \/, and "/\\" refers to /\.) The 2x2 grid is as follows:
Example 4:
1 2 3 4 5 6 7 8
Input: [ "/\\", "\\/" ] Output: 5 Explanation: (Recall that because \ characters are escaped, "/\\" refers to /\, and "\\/" refers to \/.) The 2x2 grid is as follows:
Example 5:
1 2 3 4 5 6 7
Input: [ "//", "/ " ] Output: 3 Explanation: The 2x2 grid is as follows:
classSolution { public: intregionsBySlashes(vector<string>& grid){ N = grid.size(); M = 4 * N * N; init(); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { int n = 4 * (i * N + j); if (i < N - 1) { int n_down = 4 * ((i + 1) * N + j); merge(n + 2, n_down); } if (j < N - 1) { int n_right = 4 * (i * N + j + 1); merge(n + 1, n_right + 3); } } } for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { int n = 4 * (i * N + j); if (grid[i][j] != '/') { merge(n, n + 1); merge(n + 2, n + 3); } if (grid[i][j] != '\\') { merge(n, n + 3); merge(n + 1, n + 2); } } } int result = 0; for (int i = 0; i < M; i++) { //cout << "i: " << i << ", val: " << parent[i] << endl; if (find(i) == i) { result++; } } return result; } private: int parent[3600]; int N, M; // N is grid size, M is one-dimensional size voidinit(){ for (int i = 0; i < M; i++) { parent[i] = i; } } intfind(int i){ return i == parent[i] ? i : parent[i] = find(parent[i]); } voidmerge(int x, int y){ //cout << "merge " << x << " and " << y << endl; int parent_x = find(x); int parent_y = find(y); parent[parent_x] = parent_y; } };