第12讲-简单算法实例

课件:(下载

【ZOJ1354】Extended Lights Out

#include <iostream>
#include
<cstring>
using namespace std;
#define ROW 5
#define COL 6

int lights[ROW][COL];
int ans[ROW][COL];
int temp[ROW][COL];

void Read()
{
for( int i=0;i<ROW;i++ )
{
for( int j=0;j<COL;j++ )
{
cin
>> lights[i][j];
}
}
}

void Init()
{
/*for( int i=0;i<ROW;i++ )
{
for( int j=0;j<COL;j++ )
{
temp[i][j] = lights[i][j];
ans[i][j] = 0;
}
}
*/
memcpy(temp,lights,
sizeof(lights));
memset(ans,
0,sizeof(ans));
}

void Press(int x,int y)
{
ans[x][y]
=1;
temp[x][y]
= 1-temp[x][y];
if( x>0 ) temp[x-1][y] = 1-temp[x-1][y];
if( x<ROW-1 ) temp[x+1][y] = 1-temp[x+1][y];
if( y>0 ) temp[x][y-1] = 1-temp[x][y-1];
if( y<COL-1 ) temp[x][y+1] = 1-temp[x][y+1];
}

bool OtherRows()
{
for( int i=0;i<ROW-1;i++ )
{
for( int j=0;j<COL;j++ )
{
if( temp[i][j]==1 )
Press(i
+1,j);
}
}
for( int k=0;k<COL;k++ )
{
if( temp[ROW-1][k]==1 )
return false;
}
return true;
}

void Print(int n)
{
cout
<<"PUZZLE #"<<n<<endl;
for( int i=0;i<ROW;i++ )
{
for(int j=0;j<COL;j++)
{
cout
<<ans[i][j];
if( j<COL-1 )
cout
<< " ";
}
cout
<<endl;
}
}

void FirstRow(int n)
{
for( int i=0;i<64;i++ )
{
Init();

for(int j=0;j<COL;j++)
{
if( i&(1<<j) )
{
Press(
0,j);
}
}

if(OtherRows())
{
Print(n);
return;
}
}
}

int main()
{
int n;
cin
>> n;
for(int i=1;i<=n;i++ )
{
Read();
FirstRow(i);
}
return 0;
}

 

posted @ 2010-11-29 15:47  屠一刀  阅读(255)  评论(0编辑  收藏  举报