|
| 1 | +/** |
| 2 | + * 959. Regions Cut By Slashes |
| 3 | + * https://leetcode.com/problems/regions-cut-by-slashes/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * An n x n grid is composed of 1 x 1 squares where each 1 x 1 square consists of |
| 7 | + * a '/', '\', or blank space ' '. These characters divide the square into contiguous |
| 8 | + * regions. |
| 9 | + * |
| 10 | + * Given the grid grid represented as a string array, return the number of regions. |
| 11 | + * |
| 12 | + * Note that backslash characters are escaped, so a '\' is represented as '\\'. |
| 13 | + */ |
| 14 | + |
| 15 | +/** |
| 16 | + * @param {string[]} grid |
| 17 | + * @return {number} |
| 18 | + */ |
| 19 | +var regionsBySlashes = function(grid) { |
| 20 | + const size = grid.length * 3; |
| 21 | + const matrix = new Array(size).fill().map(() => new Array(size).fill(0)); |
| 22 | + |
| 23 | + for (let row = 0; row < grid.length; row++) { |
| 24 | + for (let col = 0; col < grid.length; col++) { |
| 25 | + const baseRow = row * 3; |
| 26 | + const baseCol = col * 3; |
| 27 | + if (grid[row][col] === '/') { |
| 28 | + matrix[baseRow][baseCol + 2] = 1; |
| 29 | + matrix[baseRow + 1][baseCol + 1] = 1; |
| 30 | + matrix[baseRow + 2][baseCol] = 1; |
| 31 | + } else if (grid[row][col] === '\\') { |
| 32 | + matrix[baseRow][baseCol] = 1; |
| 33 | + matrix[baseRow + 1][baseCol + 1] = 1; |
| 34 | + matrix[baseRow + 2][baseCol + 2] = 1; |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + let result = 0; |
| 40 | + for (let row = 0; row < size; row++) { |
| 41 | + for (let col = 0; col < size; col++) { |
| 42 | + if (matrix[row][col] === 0) { |
| 43 | + helper(row, col); |
| 44 | + result++; |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + return result; |
| 50 | + |
| 51 | + function helper(x, y) { |
| 52 | + if (x < 0 || x >= size || y < 0 || y >= size || matrix[x][y] !== 0) return; |
| 53 | + matrix[x][y] = 1; |
| 54 | + helper(x + 1, y); |
| 55 | + helper(x - 1, y); |
| 56 | + helper(x, y + 1); |
| 57 | + helper(x, y - 1); |
| 58 | + } |
| 59 | +}; |
0 commit comments