Home on the Range
Farmer John grazes his cows on a large, square field N (2 <= N <= 250) miles on a side (because, for some reason, his cows will only graze on precisely square land segments). Regrettably, the cows have ravaged some of the land (always in 1 mile square increments). FJ needs to map the remaining squares (at least 2x2 on a side) on which his cows can graze (in these larger squares, no 1x1 mile segments are ravaged).
Your task is to count up all the various square grazing areas within the supplied dataset and report the number of square grazing areas (of sizes >= 2x2) remaining. Of course, grazing areas may overlap for purposes of this report.
PROGRAM NAME: range
INPUT FORMAT
| Line 1: | N, the number of miles on each side of the field. |
| Line 2..N+1: | N characters with no spaces. 0 represents "ravaged for that block; 1 represents "ready to eat". |
SAMPLE INPUT (file range.in)
6 101111 001111 111111 001111 101101 111001
OUTPUT FORMAT
Potentially several lines with the size of the square and the number of such squares that exist. Order them in ascending order from smallest to largest size.
SAMPLE OUTPUT (file range.out)
2 10 3 4 4 1
思路:
这道题的做法有很多,我相信我的思路在某些方面与众不同:
首先,maxLen[i][j]保存点(i, j)为左上角的正方形的最大边长;
加两个数组vLast1[j],hLast1[i]保存i行和j列上目前扫描到的连续的1的最远位置坐标
逐行扫描,每次扫描到一个1,往它的左上方向搜索看是否能够扩展正方形。搜索多远呢?由vLast1[j]和hLast1[i]决定:
搜索的判断条件是什么?我第一次就失误了,以为:
其实应该是:
设想在下面这种情况中:
从位置(2, 5)开始向上扩展,按照第一个判断方式,那么位置(0, 0)的点也会被糊里糊涂地加了1不是吗?而实际上这个点是不能被扩展的。
至此程序完成了,少于60行代码,时间复杂度是O(n3),而实际上(因为剪枝多)对于普通测试数据是秒杀,最后一组是最坏情况,即整张地图都是1,没有剪枝的机会,0.086s
Executing...
Test 1: TEST OK [0.000 secs, 3060 KB]
Test 2: TEST OK [0.000 secs, 3060 KB]
Test 3: TEST OK [0.000 secs, 3060 KB]
Test 4: TEST OK [0.000 secs, 3060 KB]
Test 5: TEST OK [0.000 secs, 3060 KB]
Test 6: TEST OK [0.000 secs, 3060 KB]
Test 7: TEST OK [0.086 secs, 3060 KB]

本文介绍了一个关于农场范围内剩余可耕作区域的算法问题。通过分析矩阵中的数据来确定大小至少为2x2的正方形区域数量,这些区域可用于牲畜放牧。文中详细解释了一种高效的算法实现方案,并附带完整的代码示例。
475

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



