Volver a los desafíos
Difícil 0 resueltos 0% de aceptación

Cut a Rectangle Into Squares

Find the fewest straight cuts needed to produce only squares.

Lo que aprenderás

  • Define a DP table over width and height
  • Try every horizontal and vertical cut
  • Reuse results for smaller rectangles

Problema

Ver traducción

On each move, choose one rectangle and cut all the way across it, parallel to a side, making two rectangles with positive integer side lengths. Continue until every piece is a square. Squares may have different sizes. Count cuts, not pieces.

Implement rectangle_cutting(height, width).

Input

height: The starting rectangle height.

width: The starting rectangle width.

Output

Return the minimum number of cuts.

Restricciones

1 ≤ height, width ≤ 500. Rotation does not change the answer.

Ejemplos

Ejemplo 1
Entrada:
width = 3
height = 2

Salida esperada:
expected = 2
Entrada:
long long width = 3;
long long height = 2;

Salida esperada:
long long expected = 2;
Entrada:
long width = 3;
long height = 2;

Salida esperada:
long expected = 2;

Explicación

Cut off a 2 × 2 square, leaving a 2 × 1 rectangle. One more cut splits the remainder into two unit squares.

Ejemplo 2
Entrada:
width = 4
height = 4

Salida esperada:
expected = 0
Entrada:
long long width = 4;
long long height = 4;

Salida esperada:
long long expected = 0;
Entrada:
long width = 4;
long height = 4;

Salida esperada:
long expected = 0;

Explicación

The starting rectangle is already a square.

Cómo abordarlo

Inténtalo primero por tu cuenta y luego abre las pistas una a una.

Pista 1

A rectangle can be solved by splitting it into two smaller rectangles and combining their best answers.

Pista 2

Try every possible horizontal and vertical cut to find the minimum.

Pista 3

Memoization or a table is helpful because many subrectangles repeat.

Complejidad esperada

O(h*w*(h+w)) time, O(h*w) extra space

Referencias

Este reto está adaptado para CodeUtility. Sigue el enunciado y las restricciones indicadas arriba.

Aprende de otros

Soluciones de la comunidad

Aún no hay soluciones publicadas. Resuelve este reto para compartir la primera.