Problem Statement | |||||||||||||
|
Given the width and height of a rectangular grid, return the total number of rectangles (NOT counting squares) that can be found on this grid. For example, width = 3, height = 3 (see diagram below): __ __ __ |__|__|__| |__|__|__| |__|__|__| In this grid, there are 4 2x3 rectangles, 6 1x3 rectangles and 12 1x2 rectangles. Thus there is a total of 4 + 6 + 12 = 22 rectangles. Note we don't count 1x1, 2x2 and 3x3 rectangles because they are squares. | |||||||||||||
Definition | |||||||||||||
| |||||||||||||
Notes | |||||||||||||
| - | rectangles with equals sides (squares) should not be counted. | ||||||||||||
Constraints | |||||||||||||
| - | width and height will be between 1 and 1000 inclusive. | ||||||||||||
Examples | |||||||||||||
| 0) | |||||||||||||
| |||||||||||||
| 1) | |||||||||||||
| |||||||||||||
| 2) | |||||||||||||
| |||||||||||||
| 3) | |||||||||||||
| |||||||||||||
| 4) | |||||||||||||
| |||||||||||||
This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2003, TopCoder, Inc. All rights reserved.
这道题开始写了4个for循环,结果运行592*964的时候,就卡在那里了,
这个没通过
package srms1_20_r5;
public class RectangularGrid2 {
/**
* @param args
*/
public static void main(String[] args) {
long l = countRectangles(5, 2);
System.out.println(l);
}
public static long countRectangles(int width, int height) {
long num = 0;
int stepWidth, stepHeight, x, y, endWidth, endHeight;
for (int i = 1; i <= width; i++) {
stepWidth = i;
x = 0;
for (; x + stepWidth <= width; x++) {
endWidth = x + stepWidth;
for (int j = 1; j <= height; j++) {
if (j == i)
continue;
stepHeight = j;
y = 0;
for (; y + stepHeight <= height; y++) {
num++;
}
}
}
}
return num;
}
}
后来想想,换了一套思路,确实容易了不少
public class RectangularGrid {
public long countRectangles(int width, int height) {
long num = 0;
long w[] = new long[width];
long h[] = new long[height];
for (int i = 0; i < width; i++)
w[i] = width - i;
for (int j = 0; j < height; j++)
h[j] = height - j;
for (int i = 0; i < width; i++)
for (int j = 0; j < height; j++)
if (i == j)
continue;
else
num += w[i] * h[j];
return num;
}
}
本文提供了解决矩形网格中非正方形矩形总数的算法,包括示例和代码实现,涉及宽度和高度为1至1000的矩形网格。
817

被折叠的 条评论
为什么被折叠?



