Advertisement
1988coder

750. Number Of Corner Rectangles

Feb 3rd, 2019
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.37 KB | None | 0 0
  1. // LeetCode URL: https://leetcode.com/problems/number-of-corner-rectangles/
  2.  
  3. /**
  4.  * To find an axis-aligned rectangle, the idea is to fix two rows (or two
  5.  * columns) first, then check column by column (or row by row) to find "1" on
  6.  * both rows. Say you find n pairs, then just pick any 2 of those to form an
  7.  * axis-aligned rectangle
  8.  *
  9.  * Time Complexity: O(max(R,C) * (min(R,C))^2)
  10.  *
  11.  * Space Complexity: O(1)
  12.  */
  13. class Solution {
  14.     public int countCornerRectangles(int[][] grid) {
  15.         if (grid == null || grid.length <= 1 || grid[0].length <= 1) {
  16.             return 0;
  17.         }
  18.  
  19.         int rows = grid.length;
  20.         int cols = grid[0].length;
  21.  
  22.         return rows <= cols ? util(grid, rows, cols, true) : util(grid, cols, rows, false);
  23.     }
  24.  
  25.     private int util(int[][] grid, int m, int n, boolean isRowSmall) {
  26.         int result = 0;
  27.  
  28.         for (int i = 0; i < m - 1; i++) {
  29.             for (int j = i + 1; j < m; j++) {
  30.                 int counter = 0;
  31.                 for (int k = 0; k < n; k++) {
  32.                     if (isRowSmall) {
  33.                         counter += (grid[i][k] & grid[j][k]);
  34.                     } else {
  35.                         counter += (grid[k][i] & grid[k][j]);
  36.                     }
  37.                 }
  38.                 result += counter * (counter - 1) / 2;
  39.             }
  40.         }
  41.  
  42.         return result;
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement