#include "StdAfx.h"
#include "mpi.h"
#include<stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
#include<iostream>
using namespace std;
#define N 16
#define numprocs 4
int myid, numproc;
MPI_Status status;
void display(int map[N][N])
{if (myid>0) return;
for(int i=0;i<N;i++)
{ for(int j=0;j<N;j++)
cout<<" "<<map[i][j];
cout<<endl;
}
}
void init(int map[N][N], int prob)
{ srand(time(NULL));
for(int i=0;i<N;i++)
for(int j=0;j<N;j++)
if (rand()%10<prob)
map[i][j]=1;
else map[i][j]=0;
}
void dostep(int map[N][N],int area[N+2][N/numprocs+2])
{
int send[N+2],recv[N+2];
int left_rank = (myid==0?MPI_PROC_NULL : myid-1);
int right_rank = (myid==numprocs-1?MPI_PROC_NULL :myid+1);
MPI_Recv(recv, N, MPI_INT,right_rank, right_rank,
MPI_COMM_WORLD,&status);//from right
for(int i=0;i<N+2;i++)
{
send[i]=area[i][1];
area[i][N/numprocs+2]=recv[i];
}
MPI_Send(send,N,MPI_INT,left_rank,myid,MPI_COMM_WORLD);//to left
for(int i=0;i<N+2;i++)
send[i]=area[i][N/numprocs+2];
MPI_Send(send,N,MPI_INT,right_rank,myid,MPI_COMM_WORLD);//to right
MPI_Recv(recv, N, MPI_INT,left_rank, left_rank,
MPI_COMM_WORLD,&status);//from left
for(int i=0;i<N+2;i++)
area[i][0]=recv[i];
MPI_Barrier(MPI_COMM_WORLD);
for(int i=1;i<N+1;i++)
for(int j=1;j<=N/numprocs;j++)
{int neighbors=0;
for (int k=i-1;k<=i+1; k++)
for (int l=j-1;l<=j+1; l++)
if (!(k==i&&l==j)&&area[k][l]>0)
neighbors++;
if (neighbors<2||neighbors>3)