翁恺java期末考试题
作者:互联网
翁恺老师的期末考试题代码
class本来是自定义的但是不同过只能定义为Main
并且注释也无法识别会报错
这是最终提交通过的
import java.util.Scanner;
class Main
{
private int times;
private int width;
private int height;
int old_field[][];
int new_field[][];
Scanner in = new Scanner(System.in);
void Init()
{
width = in.nextInt();
height = in.nextInt();
old_field = new int[height+2][width+2];
new_field = new int[height+2][width+2];
for (int i = 0; i < height+2; i++)
for (int j = 0; j < width+2; j++)
{
old_field[i][j] = 0;
old_field[i][j] = 0;
}
while(true)
{
int i=in.nextInt();
int j=in.nextInt();
if(i==-1&&j==-1)
break;
old_field[i+1][j+1]=1;
new_field[i+1][j+1]=1;
}
times = in.nextInt();
}
void run()
{
for(int k=0;k<times;k++)
{
for(int i=1;i<height+1;i++)
{
for(int j=1;j<width+1;j++)
{
int count=getNeighbor(i, j);
if(old_field[i][j]==0)
{
if(count==3)
new_field[i][j]=1;
}
else
{
if(!(count==2||count==3))
new_field[i][j]=0;
}
}
}
//copy
for (int i = 1; i < height+1; i++)
{
for (int j = 0; j < width+1; j++)
{
old_field[i][j] = new_field[i][j];
}
}
}
}
int getNeighbor(int i,int j)
{
int temp=0;
temp+=old_field[i-1][j]+old_field[i+1][j]+old_field[i][j-1]+old_field[i][j+1];
temp+=old_field[i-1][j-1]+old_field[i-1][j+1]+old_field[i+1][j-1]+old_field[i+1][j+1];
return temp;
}
int Count()
{
int count=0;
for (int i = 1; i < height+1; i++)
{
for (int j = 1; j < width+1; j++)
{
if(old_field[i][j]==1)
count++;
}
}
return count;
}
void Test()
{
Init();
run();
System.out.println(Count());
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
new Main().Test();
}
}
标签:java,width,int,height,field,期末考试,new,old,翁恺 来源: https://blog.csdn.net/qq_26010817/article/details/113037365