這個題目思路還是比較簡單的,兩個數組儲存行和列的情況。然後再遍歷各個頂點的情況就可以了。其他的見源碼中的註釋。
#include<iostream>
#include<fstream>
using namespace std;
struct zuobao //創建結構體用來儲存橫邊和豎邊的座標
{
int row;
int column;
};
bool ifexist(int i, int j, int size, const zuobao* rc)
{
for (int m = 0; m < size; ++m)
{
if (rc[m].row == i && rc[m].column == j)
return true;
}
return false;
}
void panduan(int i, int j, int square_size, int lenth, int *number, const zuobao *r, const zuobao*c) // i爲橫座標,j爲縱座標,該函數用來計算以該點爲右上角的起點,可以構成什麼正方形
{
for (int m = 1; m < square_size; ++m) //循環判斷規格爲1--n-1的正方形
{
int key = 1; //用來標記邊是否存在
for (int n = 0; n < m; ++n) //左邊豎向的邊
{
if (!ifexist(i + n, j, lenth, c))
{
key = 0;
break; //缺少邊跳出循環
}
}
if (key == 0) //如果缺少跳過下面的判斷
continue;
for (int n = 0; n < m; ++n)
{
if (!ifexist(i + m, j + n, lenth, r))
{
key = 0;
break;
}
}
if (key == 0)
continue;
for (int n = 0; n < m; ++n)
{
if (!ifexist(i + n, j + m, lenth, c))
{
key = 0;
break;
}
}
if (key == 0)
continue;
for (int n = 0; n < m; ++n)
{
if (!ifexist(i, j + n, lenth, r))
{
key = 0;
break;
}
}
if (key == 0)
continue;
++number[m];
}
}
int main()
{
///*文件重定向,輸出測試*/
//ifstream fin;
//fin.open("data.in");
//cin.rdbuf(fin.rdbuf());
//ofstream out;
//out.open("data.out");
//cout.rdbuf(out.rdbuf());
int n = 0, m = 0, times = 1; //n爲正方體邊上點的個數,m爲邊的個數
int t = 0;
while (cin >> n >> m)
{
if (0 != t)
cout <<endl<< "**********************************" << endl << endl;
t = 1;
char kind;
zuobao * r = new zuobao[m + 2]; //r爲橫邊,c爲豎邊
zuobao * c = new zuobao[m + 2];
int number[12] = { 0 }; //統計不同規格的正方形的個數
for (int i = 0; i < m; ++i)
{
cin >> kind;
if(kind=='H')
cin >> r[i].row >> r[i].column;
else
cin >> c[i].column >> c[i].row;
} //注意這裏題目裏的i變成了列,而j變成了行,注意調換順序
cout << "Problem #" << times << endl << endl;
++times;
for (int i = 1; i < n; ++i)
for (int j = 1; j < n; ++j)
{
panduan(i, j, n, m, number, r, c);
}
int temp = 0;
for (int i = 1; i < n; ++i)
{
if (number[i] != 0)
{
cout << number[i] << " square (s) of size " << i << endl;
temp = 1;
}
}
if (0 == temp)
cout << "No completed squares can be found." << endl;
}
}
前面的題目的一些代碼在gihub的倉庫裏https://github.com/YinAoXiong/Algorithmic-exercises,(全部都是用vs寫的工程文件,源文件在同名的子目錄目錄中)。如有不對的地方歡迎大家評論指正,這裏是我在github上的一個博客,感興趣的可以去看一下哦。