C++中的对称矩阵
Symmetric Matrix in C++
检查二维矩阵是否对称任务是输出 YES 如果矩阵是对称的,否则输出 NO。
我没有得到预期的结果。有人可以帮我,请让我知道这段代码有什么问题吗
#include<iostream>
#include<vector>
using namespace std;
bool rev(int n)
{
int n1,d,rn=0;
n1=n;
while(n>0)
{
d=n%10;
rn=(rn*10)+d;
n/=10;
}
if(n1==rn)
{return true;}
else
return false;
}
bool XAxisSymCheck(vector<int> vect)
{
// Declaring iterator to a vector
vector<int>::iterator ptr;
for (ptr = vect.begin(); ptr < vect.end(); ptr++)
{ if(!rev(*ptr)) // reversing the elements in each element of vector to check whether its symmetric or not .. similar to palindrome
{
return false;
}
}
}
int main()
{int testcase;
cin>>testcase;
for(int k=0;k<testcase;++k)
{vector<int> rows;
bool IsSymmetric=true;
int row;
cin >> row;
// read each row and append to the "rows" vector
for (int r = 0; r < row; r++)
{
int line;
cin >> line;
rows.push_back(line);
}
if(XAxisSymCheck(rows))
{int i,j;
i=0;
j=row-1;
while(i<j) // looping through the elements of vector and checking the first element with last element , second element with the second last element and so on.
{
if(rows[i]!=rows[j])
{
IsSymmetric=false;
break;
}
i++;
j--;
}
}
else
{
IsSymmetric=false;
}
cout << (IsSymmetric ? "Yes" : "No") << endl;
}
return 0;
}
输入:第一行包含 T - 测试用例数。接下来是 T 个测试用例。每个测试用例的第一行包含矩阵的 N - 大小。接下来的 N 行包含长度为 N 的二进制字符串。
输出:在每个测试用例的新行中打印"是"或"否">
SAMPLE INPUT
5
2
11
11
4
0101
0110
0110
0101
4
1001
0000
0000
1001
5
01110
01010
10001
01010
01110
5
00100
01010
10001
01010
01110
SAMPLE OUTPUT
YES
NO
YES
YES
NO
Test Case #1: Symmetric about both axes, so YES.
Test Case #2: Symmetric about X-axis but not symmetric about Y-axis, so NO.
Test Case #3: Symmetric about both axes, so YES.
Test Case #4 and #5 are explained in statement.
你的代码有三个问题
1(您永远不会从XAxisSymCheck
返回true
(这可以通过检查编译器警告轻松发现,例如g++ -Wall matrix.cpp
(
bool XAxisSymCheck(vector<int> vect) {
vector<int>::iterator ptr;
for (ptr = vect.begin(); ptr < vect.end(); ptr++) {
if(!rev(*ptr, vect.size()))
return false;
}
return true;
}
2(当你的XAxisSymCheck
失败时,你没有将IsSymmetric
设置为false
(至少在编辑前的原始帖子中(
for(int k=0;k<testcase;++k) {
vector<int> rows;
bool IsSymmetric = true;
// ....
if (XAsxisSymCheck(rows)) {
// ...
} else {
IsSymmetric = false;
}
cout << (IsSymmetric ? "Yes" : "No") << endl;
}
3(如果一行有前导零,你的反向检查失败,因为反向的乘以10的频率不够高。
bool rev(int n,int len) {
int n1,d,rn=0;
n1=n;
for (int i = 0; i < len; i++)
{
d=n%10;
rn=(rn*10)+d;
n/=10;
}
return n1==rn;
}
相关文章:
- 两个数字的对称配对功能
- 找到对称矩阵的最大元素的最有效算法是什么
- 稀疏对称矩阵初始化
- std::shared_ptr 和 std::unique_ptr 构造函数之间的不对称
- 离散分布不对称
- 在 c++ 中查找对称矩阵的正交基
- 迭代特征中的对称稀疏矩阵
- 在加密++中使用RSA加密对称AES密钥
- 矢量化对称矩阵
- 如何安全地存储对称键?我可以使用PKCS12存储对称键
- 用于检查二叉树是否对称的技术
- 使用数组填充对称矩阵
- 如何在C++特征中交换对称稀疏矩阵中的列和行?
- C++中的对称矩阵
- 使用 SIMD AVX 计算两个排序数组的对称差的大小
- 特征3中对称矩阵的行列式
- 如果矩阵密集且不对称,特征库矩阵/矢量操作是否比 .net 矩阵/向量操作更快?
- 使用结构进行反射,对称或及时的测试集
- 这是光谱库中最快的特征值求解器,适用于巨大的稀疏对称矩阵
- 一种使用 unordered_map 表示对称稀疏矩阵的有效方法