|
| 1 | +/** |
| 2 | + * 533. Lonely Pixel II |
| 3 | + * https://leetcode.com/problems/lonely-pixel-ii/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given an m x n picture consisting of black 'B' and white 'W' pixels and an integer target, |
| 7 | + * return the number of black lonely pixels. |
| 8 | + * |
| 9 | + * A black lonely pixel is a character 'B' that located at a specific position (r, c) where: |
| 10 | + * - Row r and column c both contain exactly target black pixels. |
| 11 | + * - For all rows that have a black pixel at column c, they should be exactly the same as row r. |
| 12 | + */ |
| 13 | + |
| 14 | +/** |
| 15 | + * @param {character[][]} picture |
| 16 | + * @param {number} target |
| 17 | + * @return {number} |
| 18 | + */ |
| 19 | +var findBlackPixel = function(picture, target) { |
| 20 | + const rows = picture.length; |
| 21 | + const cols = picture[0].length; |
| 22 | + const rowCounts = new Array(rows).fill(0); |
| 23 | + const colCounts = new Array(cols).fill(0); |
| 24 | + const rowPatterns = new Map(); |
| 25 | + |
| 26 | + for (let row = 0; row < rows; row++) { |
| 27 | + let blackCount = 0; |
| 28 | + for (let col = 0; col < cols; col++) { |
| 29 | + if (picture[row][col] === 'B') { |
| 30 | + blackCount++; |
| 31 | + colCounts[col]++; |
| 32 | + } |
| 33 | + } |
| 34 | + rowCounts[row] = blackCount; |
| 35 | + if (blackCount === target) { |
| 36 | + const pattern = picture[row].join(''); |
| 37 | + rowPatterns.set(pattern, (rowPatterns.get(pattern) || 0) + 1); |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + let result = 0; |
| 42 | + for (let col = 0; col < cols; col++) { |
| 43 | + if (colCounts[col] === target) { |
| 44 | + for (let row = 0; row < rows; row++) { |
| 45 | + if (picture[row][col] === 'B' && rowCounts[row] === target) { |
| 46 | + const pattern = picture[row].join(''); |
| 47 | + if (rowPatterns.get(pattern) === target) { |
| 48 | + result += target; |
| 49 | + break; |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + return result; |
| 57 | +}; |
0 commit comments