刘汝佳算法入门笔记(1)

刘汝佳算法入门笔记

  • 习题4-2

习题4-2

有n行n列(2≤n≤9)的小黑点,还有m条线段连接其中的一些黑点。统计这些线段连成 了多少个正方形(每种边长分别统计)。 行从上到下编号为1~n,列从左到右编号为1~n。边用H i j和V i j表示,分别代表边(i,j)-(i,j+1)和(i,j)-(i+1,j)。如图4-5所示最左边的线段用V 1 1表示。图中包含两个边长为1的正方形和一个边长为2的正方形。

刘汝佳算法入门笔记(1)_第1张图片

#include
#include
#include

#define maxn 9
#define minn 2

int v[maxn][maxn], h[maxn][maxn];
int point[maxn][maxn] = { 0 };

int length, height = 0;


void build();
void count();

int main(void)
{

	while (1)
	{
		build();
		count();
	}

	system("pause");
	return 0;
}

void build()
{
	printf("please input the length and height:");
	scanf_s("%d%d", &length, &height);
	for (int i = 0; i < height; i++)
	{
		for (int j = 0; j < length; j++)
		{
			printf("(%d,%d)", i, j);
			scanf_s("%d%d", &v[i][j], &h[i][j]);
		}
	}
	printf("the graph is build\n");

	for (int i = 0; i < height; i++)
	{
		for (int j = 0; j < length; j++)
		{
			if (h[i][j])
				printf(" — ");
			else
				printf("   ");
		}
		printf("\n");
		for (int j = 0; j < length; j++)
		{
			if (v[i][j])
				printf("|  ");
			else
				printf("   ");
		}
		printf("\n");
	}
}

int square_num[maxn] = { 0 };
int squareNum(int len);
void count()
{
	int maxLen = length - 1;
	int maxHgt = height - 1;
	int len = maxLen < maxHgt ? maxLen : maxHgt;

	for (int i =1; i <= len; i++)
	{
		square_num[i] = squareNum(i);
		printf("len:%d ,square:%d\n", i , square_num[i]);
	}
}
int squareNum(int len)
{
	int count = 0;
	int test = 0;
	int t = 0;
	for (int i = 0; i < height; i++)
	{
		for (int j = 0; j < length; j++)
		{
			for (t = 0; t < len; t++)
			{
				if (v[i + t][j] && v[i + t][j + len] && h[i][j + t] && h[i + len][j + t])
					test++;
				//else test = 0;
			}
			if (test == len)
				count++;
			test = 0;
		}
	}
	return count;
}

你可能感兴趣的:(算法练习)