1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| #include <iostream> #include <queue> using namespace std;
const int N = 25;
int colP[N],rowP[N];
int dst[N][N];
int ox[4]={0,0,-1,1},oy[4]={1,-1,0,0};
deque<int> path;
int n;
bool checkComp(){ for(int i=0;i<n;i++) { if(colP[i]!=0||rowP[i]!=0) return false; } return true; }
bool check(int x,int y){ return x>=0&&x<n&&y>=0&&y<n; }
void dfs(int x,int y){ rowP[x] --,colP[y]--; dst[x][y] = 1; path.push_back(n*x+y);
if(x==n-1&&y==n-1&&checkComp()){ while (!path.empty()) { printf("%d", path.front()); path.pop_front(); printf(path.empty() ? "\n" : " "); } exit(0); } for(int i=0;i<4;i++){ int nx = x+ox[i],ny=y+oy[i]; if(check(nx,ny)&&!dst[nx][ny]&& rowP[nx]>0&&colP[ny]>0){ dfs(nx,ny); path.pop_back(); dst[nx][ny] = 0; ++rowP[nx],++colP[ny]; } } }
int main(){ cin>>n; for(int i=0;i<n;i++) cin>>colP[i]; for(int i=0;i<n;i++) cin>>rowP[i]; dfs(0,0); return 0; }
|