在一个5 * 5的矩阵中,给定一个长度为 6的数组,判定这数组的值是否在矩阵中相连的,如
如矩阵:
int m[5][5] =
{
{1, 2, 3, 4, 5},
{11,12,13,14,15},
{21,22,23,24,25},
{31,32,33,34,35},
{41,42,43,44,45}
};
给定数组 [ 12, 3, 13, 23, 15, 14 ] ,输出为 true
给定数组 [ 12, 3, 13, 23, 14, 15 ] ,输出为 true
给定数组 [ 12, 3, 13, 23, 14, 25] ,输出为 false
给定数组 [ 12, 3, 13, 23, 14, 5] ,输出为 false
下图是相连的情况:
解:
主要思路:若 A和B相连,B和C相连,则A和C也相连,将给定数组元素相连通的放到一起,剩下还有,则不连通。
C++代码:
#include
#include
using namespace std;
#define LEN 5
#define LEN1 6
bool findOne(int p[][LEN],int target)
{
int site = -1;
for(int i = 0; i < LEN; i++)
{
for(int j = 0; j < LEN; j++)
{
if(target == p[i][j])
{
site = i * LEN + j;
return site;
}
}
}
return site;
}
int findNeb(int m[][LEN],int site,int target)
{
int a = site / 5;
int b = site % 5;
site = -1;
if((a-1) >= 0 && m[a-1][b] == target)
{
a = a -1;
site = a * 5 + b;
}
else if((a+1) < 6 && m[a+1][b] == target)
{
a = a + 1;
site = a * 5 + b;
}
else if((b-1) >= 0 && m[a][b-1] == target)
{
b = b - 1;
site = a * 5 + b;
}
else if((b+1) < 6 && m[a][b+1] == target)
{
b = b + 1;
site = a * 5 + b;
}
else
{
site = -1;
}
return site;
}
int main()
{
int m[LEN][LEN] =
{
{1, 2, 3, 4, 5},
{11,12,13,14,15},
{21,22,23,24,25},
{31,32,33,34,35},
{41,42,43,44,45}
};
int tmp[LEN1] = {-1};
int a = 0;
int len = 0;
while(cin >> a)
{
tmp[len] = a;
if(len < LEN1-1)
{
len ++;
continue;
}
len = 0;
for(int i = 0; i < LEN1; i++)
cout<<tmp[i]<<" ";
cout<<endl;
len = 0;
int site = -1;
if((site = findOne(m,tmp[0])) == -1)
{
cout<<"Not find [0]"<<endl;
return 0;
}
queue<int> qSite;
qSite.push(site);
tmp[0] = -1;
while(!qSite.empty())
{
for(int i = 1;i < LEN1;i++)
{
site = qSite.front();
if(tmp[i] != -1 && (site = findNeb(m,site,tmp[i])) != -1) // find neb, if have neb and let it in
{
qSite.push(site);
tmp[i] = -1;
}
}
qSite.pop();
}
// check the member no neb
bool flag = true;
for(int i = 0; i < LEN1; i++)
{
if(tmp[i] != -1)
{
flag = false;
break;
}
}
cout<<"result:"<<flag<<endl;
}
}