初来报道,问一个算法问题。

TinkyWinky 2008-04-26 01:45:59
请问这题应该用什么算法解决?
You are given a M*M cloth with some holes on it.Your task is to find a biggest square cloth from it.

Input
There are several test cases.For each case,the first line contains the one integer number M(1<=M<=1000).Then M lines are following.Each line contains M characters which "." means cloth and "H" means hole.When M=0,it means the end of the input.

Out put
For each test case,your program should output the only line containing the area of the biggest square cloth.

Sample Input
5
H...H
.....
.....
.HHH.
.....
4
....
.HH.
....
0

Sample Output
9
1
...全文
122 7 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
lzr001 2008-04-29
  • 打赏
  • 举报
回复
每读入一个字符,即计算出以当前点为右下角的最大的正方型,
计算时依据三个点,左边的点/上边的点/左上方的点,
例如:
A B
C D
A/B/C分别代表当前点D的左上面/上面/左面所能组成的最大正方型,
然后取A B C最小值,最小值+1即为D点所能组成的最大正方型。

动态规划,从上到下,从左到右,即算出全部点的正方型,然后取出最大值输出即可!
计算过程中不用保存全部点的值,只需保存上一行的结果就可以了,
算法复杂度O(N*N),空间复杂度O(2*N)
TinkyWinky 2008-04-27
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 lzr001 的回复:]
动态规划
贴个程序上来,大家看看有没有问题!
另,LZ的输入有问题吧,第二套输入只有12个字符


#include <iostream>

using namespace std;

const unsigned long MAX_SIZE = 1000;

int main()
{
int result[MAX_SIZE+1] = {0};
int M = 0;

while (cin >> M) {
if (M <= 0)break;

int maxCloth = 0; //最大值
int curResult = 0; //当前…
[/Quote]

晕。真的输错了。更正如下:
Sample Input
5
H...H
.....
.....
.HHH.
.....
4
....
.HH.
.HH.
....
0

Sample Output
9
1

另,能具体说一下算法的思想吗?
TinkyWinky 2008-04-26
  • 打赏
  • 举报
回复
不是搜索出来的,是我上次比赛没做出来的题目。这道题要求程序5秒内输出答案。
lzr001 2008-04-26
  • 打赏
  • 举报
回复
动态规划
贴个程序上来,大家看看有没有问题!
另,LZ的输入有问题吧,第二套输入只有12个字符


#include <iostream>

using namespace std;

const unsigned long MAX_SIZE = 1000;

int main()
{
int result[MAX_SIZE+1] = {0};
int M = 0;

while (cin >> M) {
if (M <= 0)break;

int maxCloth = 0; //最大值
int curResult = 0; //当前节点值
int preResult = 0; //左面节点值

for (int i = 0; i < M; ++i) {
preResult = 0;
int tempResult[MAX_SIZE+1] = {0};

for (int j = 0; j < M; ++j) {
char c;
cin >> c;

if (c == 'H') {
preResult = 0;
tempResult[j] = 0;
continue;
}
//c == '.'
else {
curResult = 1;
if (curResult > maxCloth)maxCloth = curResult;
if (j == 0 || i == 0)tempResult[j] = curResult;
else {
//查找左面/上面/左上三个节点的最小值
int minResult = preResult;
minResult = min(minResult, result[j]);
minResult = min(minResult, result[j-1]);

//当前节点比最小值大1,也就是可以组成大一个单位的正方型
tempResult[j] = minResult + 1;
preResult = tempResult[j];
if (tempResult[j] > maxCloth)maxCloth = tempResult[j];
}
}
}

for (int j = 0; j < M; ++j)result[j] = tempResult[j];
}

cout << maxCloth * maxCloth << endl;
}
return 0;
}
feir8510 2008-04-26
  • 打赏
  • 举报
回复
acm题目啊,搜索出的来么?感觉1000宽度能把,感觉可以跳跃搜,不过时间复杂度还是提不上来啊。
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 TinkyWinky 的回复:]
UP
[/Quote]
TinkyWinky 2008-04-26
  • 打赏
  • 举报
回复
UP

33,321

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧