清北暑假模拟day2 将

/*
爆搜,正解弃坑
*/
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
#include<stack>
using namespace std;
const int maxn = 20;
int n,m,x1[maxn],y1[maxn],x2[maxn],y2[maxn],vis[maxn][maxn],p[maxn][maxn],l[maxn];
bool dfs(int col,int stp,int y,int x){
    if(y == y2[col] && x == x2[col]){
        l[col] = stp;
        if(col == m){
            int tmpl = 0;
            for(int i = 1;i <= m;i++) tmpl += l[i];
            if(tmpl == n*n) return true;
            else return false;
        }
        return dfs(col+1,1,y1[col+1],x1[col+1]);
    }
    vis[y][x] = col;
    int ty,tx;
    for(int i = 2;i <= 8;i+=2){
        if(i == 2){
            ty = y - 1;
            tx = x;
        }else if(i == 4){
            ty = y;
            tx = x - 1;
        }else if(i == 6){
            ty = y;
            tx = x + 1;
        }else{
            ty = y + 1;
            tx = x;
        }
        if(ty < 1 || ty > n || tx < 1 || tx > n || (vis[ty][tx] && (ty != y2[col] || tx != x2[col]))) continue;
        p[y][x] = i;
        if(dfs(col,stp+1,ty,tx)) return true;
    }
    if(y != y1[col] || x != x1[col])vis[y][x] = 0;
    return false;
}
int main(){
    freopen("jian.in","r",stdin);
    freopen("jian.out","w",stdout);
    cin>>n>>m;
    for(int i = 1;i <= m;i++){
        cin>>x1[i]>>y1[i]>>x2[i]>>y2[i];
        vis[y1[i]][x1[i]] = vis[y2[i]][x2[i]] = i;
    }
    dfs(1,1,y1[1],x1[1]);
    int nowy,nowx;
    for(int i = 1;i <= m;i++){
        cout<<l[i]<<endl;
        nowy = y1[i];
        nowx = x1[i];
        for(int j = 1;j <= l[i];j++){
            cout<<nowx<<" "<<nowy<<endl;
            if(p[nowy][nowx] == 2) nowy--;
            else if(p[nowy][nowx] == 4) nowx--;
            else if(p[nowy][nowx] == 6) nowx++;
            else if(p[nowy][nowx] == 8) nowy++;
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/hyfer/p/5978438.html