1. 程式人生 > >201512-2-消除類遊戲-CCF

201512-2-消除類遊戲-CCF

題目:http://118.190.20.162/view.page?gpid=T36

解題思路:(100分,正解)建兩個二維陣列,一個用來做判斷,一個用來操作(修改)。
 

#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
using namespace std;
#define per(i,a,b) for(int i=a;i<b;i++)
#define rep(i,b,a) for(int i=b;i>=a;i--)
const int N=31;
int q[N][N],q1[N][N];
int n,m;
int main(){
cin>>n>>m;
per(i,0,n)
per(j,0,m){
cin>>q[i][j];
q1[i][j]=q[i][j];
}
int num=0;
per(i,0,n){
 per(j,1,m){
     if(q1[i][j-1]==q1[i][j]){
        num++;
        if(num>=2){
            q[i][j]=0;
            q[i][j-1]=0;
            q[i][j-2]=0;
        }
     }
     else{
        num=0;
     }
 }
 num=0;
}
num=0;
per(j,0,m){
    per(i,1,n){
     if(q1[i-1][j]==q1[i][j]){
        num++;
        if(num>=2){
            q[i][j]=0;
            q[i-1][j]=0;
            q[i-2][j]=0;
        }
     }
     else {
            num=0;
     }
    }
    num=0;
}
per(i,0,n)
per(j,0,m){
    cout<<q[i][j];
    if(j!=m-1) cout<<" ";
    else cout<<endl;
}
return 0;
}

剛開始沒認真讀題和好好看樣例,想到了dfs,寫完後,看到和樣例不一樣,便趕緊改。以下為錯解,只為做自己的記錄。

#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
using namespace std;
#define per(i,a,b) for(int i=a;i<b;i++)
#define rep(i,b,a) for(int i=b;i>=a;i--)
const int N=31;
int x[4]={1,0,-1,0};
int y[4]={0,1,0,-1};
int q[N][N];
bool vis[N][N];
bool flag;
int n,m,num;
void dfs(int a,int b){
    vis[a][b]=true;
    num++;
    if(num>=3){
        flag=true;
    }
    per(i,0,4){
        int nx=a+x[i];
        int ny=b+y[i];
        if(q[nx][ny]&&q[nx][ny]==q[a][b]&&!vis[nx][ny]){
            dfs(nx,ny);
        }
    }
    if(flag)q[a][b]=0;
}
int main(){
cin>>n>>m;
per(i,0,n)
per(j,0,m)
cin>>q[i][j];
memset(vis,false,sizeof(vis));
per(i,0,n)
per(j,0,m)
{
    flag=false;
    num=0;
    dfs(i,j);
}
per(i,0,n)
per(j,0,m){
cout<<q[i][j];
if(j!=m-1) cout<<" ";
else cout<<endl;
}
return 0;
}