PAT T1012 Greedy Snake

直接暴力枚举,注意每次深搜完状态的还原~

#include<bits/stdc++.h>
using namespace std;
const int maxn=1014;
int visit[maxn][maxn];
int N,M,x,y;
int cnt;
int maxcnt;
int X[4]={1,0,-1,0};
int Y[4]={0,1,0,-1};
int judge (int x,int y) {
    if (x<1||x>N||y<1||y>N) return 0;
    if (visit[x][y]) return 0;
    return 1;
}
void dfs (int x,int y,int pre) {
    visit[x][y]=1;
    cnt++;
    int tx=x+X[pre];
    int ty=y+Y[pre];
    if (judge(tx,ty)) dfs (tx,ty,pre);
    else {
        int flag=0;
        for (int i=0;i<4;i++) {
            tx=x+X[i];
            ty=y+Y[i];
            if (judge(tx,ty)) flag++,dfs(tx,ty,i);
        }
        if (flag==0) maxcnt=max(maxcnt,cnt);
    }
    visit[x][y]=0;
    cnt--;
}
int main () {
    scanf ("%d %d",&N,&M);
    N-=2;
    for (int i=0;i<M;i++) {
        scanf ("%d %d",&x,&y);
        x--;
        y--;
        visit[x][y]=1;
    } 
    int ans=0;
    int num=0;
    for (int i=1;i<=N;i++) {
        for (int j=1;j<=N;j++) {
            if (judge(i,j)) {
                maxcnt=0;
                dfs (i,j,0);
                dfs (i,j,1);
                dfs (i,j,2);
                dfs (i,j,3);
                if (maxcnt>ans) {
                    ans=maxcnt;
                    num=1;
                }
                else if (maxcnt==ans) {
                    num++;
                }
            }
        }
    }
    printf ("%d %d\n",N*N-ans-M,num);
    num=0;
    int ans1=0;
    for (int i=1;i<=N;i++) {
        for (int j=1;j<=N;j++) {
            if (visit[i][j]) continue;
            visit[i][j]=1;
            maxcnt=0;
            for (int k=1;k<=N;k++) {
                for (int w=1;w<=N;w++) {
                    if (judge(k,w)) {
                        dfs (k,w,0);
                        dfs (k,w,1);
                        dfs (k,w,2);
                        dfs (k,w,3);
                    }
                }
            }
            if (maxcnt>ans1) {
                ans1=maxcnt;
                num=1;
            }
            else if (maxcnt==ans1) {
                num++;
            }
            visit[i][j]=0;
        }
    }
    if (ans1<ans) printf ("-1");
    else printf ("%d %d\n",N*N-M-ans1-1,num);
    return 0;
}

 

posted @ 2020-02-13 11:33  zlc0405  阅读(220)  评论(0编辑  收藏  举报