Find largest cuboid containing only 1's in an NxNxN binary array

后端 未结 2 1012
醉酒成梦
醉酒成梦 2021-01-31 21:45

Given an NxNxN binary array (containing only 0\'s or 1\'s), how can we obtain the largest cuboid with a non-trivial solution i.e. in O(N^3) ?

--

It is the same p

2条回答
  •  广开言路
    2021-01-31 22:21

    Here is only O(N^4).

    Lets assume you are storing cubiod in bool cuboid[N][N][N];

    bool array2d[N][N];
    
    for(int x_min = 0; x_min < N; x_min++) {
       //initializing array2d
       for(int y = 0; y < N; y++) {
          for(int z = 0; z < N; z++) {
             array2d[y][z] = true;
          }
       }
    
       //computation
       for(int x_max = x_min; x_max < N; x_max++) {
          // now we want to find largest cube that
          // X coordinates are equal to x_min and x_max
    
          // cells at y,z can be used in cube if and only if
          // there are only 1's in cuboid[x][y][z] where x_min <= x <= x_max
    
          // so lets compute for each cell in array2d,
          // if are only 1's in cuboid[x][y][z] where x_min <= x <= x_max
          for(int y = 0; y < N; y++) {
             for(int z = 0; z < N; z++) {
                array2d[y][z] &= cubiod[x_max][y][z];
             }
          }
    
          //you already know how to find largest rectangle in 2d in O(N^2)
          local_volume = (x_max - x_min + 1) * find_largest_area(array2d);
    
          largest_volume = max(largest_volumne, local_volume);
       }
    }
    

    You can use the same trick, to compute best solution in X dimentions. Just reduce the problem to X-1 dimensions. Complexity: O(N^(2*X-2)).

提交回复
热议问题