下面是我在貼吧看到的一個題,我試着編了下,如果你有更好的解法,請回復我!!!
數組如下:
#include<iostream>
using namespace std;
int main()
{
int a[6][6]={{1,1,1,0,0,0},
{0,0,0,0,0,1},
{1,0,1,1,1,0},
{0,1,1,1,1,0},
{1,0,0,1,0,1},
{0,0,1,1,0,0}};
return 0;
}
示例1:如果x=3,y=3,就是選取了a[3][3]這個點,和他相關相同值的點有a[3,4],a[3,5],a[4,1],a[4,2],a[4,3],a[4,4],a[5,3],a[6,2],a[6,3],加上自己,總共有10個點。
示例2:如果x=0,y=0,就是選擇了a[0][0]這個點,和他相關相同值的點有a[0,1],a[0,2],a[0,3],a[0,4],a[1,1],加上自己,總共有6個點。
輸入x,y,求出相同點數。
#include <iostream>
using namespace std;
void shuchu(int x,int y); //輸出區域中的座標
int panduan(int x,int y); //判斷座標已經存在
void cunfang(int x,int y);//存放數據到fuzhu數組中
typedef struct
{
int hen;//hen爲橫座標
int zon;//zon爲縱座標
}f;//記錄每個域的值
f fuzhu[36];//最多連續36個點
static int count=0;//記錄座標的個數(cout+1)
int shuju[6][6]= //這個二維數組可自由變動,以下的數據是我隨便打的
{
{0,1,0,1,1,1},
{0,0,0,0,1,0},
{1,1,1,1,1,0},
{1,0,1,0,1,0},
{1,0,1,0,0,0},
{0,0,0,0,1,1}
};
int main()
{ int x1,y1;//x爲橫座標,y爲縱座標
int i,j;
cout<<"這個區域的數據:"<<endl<<endl;
for(i=0;i<6;i++)
{
for(j=0;j<6;j++)
{
cout<<shuju[i][j]<<" ";
}cout<<endl;
}
cout<<endl<<"輸入座標x,y的值:";
cin>>x1>>y1;
fuzhu[0].hen=x1;fuzhu[0].zon=y1;
shuchu(x1,y1);
cout<<"四周連續相同點數是: "<<count<<endl;
for(i=0;i<=count;i++)
{
cout<<"("<<fuzhu[i].hen<<","<<fuzhu[i].zon<<")";
if(i%4==0)cout<<endl;
}
cout<<endl;
system("pause");
return 0;
}
int panduan(int a,int b) //等於1時,fuzhu數組中不存在這個座標
{ int i;
for (i=0;i<count;i++)
{
if (fuzhu[i].hen==a&&fuzhu[i].zon==b)
{
return 0;
}
}
return 1;
}
void cunfang(int a,int b)
{
fuzhu[count].hen=a;
fuzhu[count].zon=b;
}
void shuchu(int x,int y)
{
if((shuju[x][y+1]==shuju[x][y])&&(-1<y+1)&&(y+1<6)) //判斷這個座標上方的值是否等於這個座標值並且防止這個座標超出範圍
{
if(panduan(x,y+1)==1)
{
count++;
cunfang(x,y+1);
shuchu(x,y+1);
}
}
if((shuju[x-1][y]==shuju[x][y])&&(-1<x-1)&&(x-1<6))
{
if(panduan(x-1,y)==1)
{
count++;
cunfang(x-1,y);
shuchu(x-1,y);
}
}
if((shuju[x+1][y]==shuju[x][y])&&(-1<x+1)&&(x+1<6))
{
if(panduan(x+1,y)==1)
{
count++;
cunfang(x+1,y);
shuchu(x+1,y);
}
}
if((shuju[x][y-1]==shuju[x][y])&&(-1<y-1)&&(y-1<6))
{
if(panduan(x,y-1)==1)
{
count++;
cunfang(x,y-1);
shuchu(x,y-1);
}
}
}
下面爲運行結果: