#include<bits/stdc++.h>
using namespace std;
const int N = 30;
//行与列上的箭数
int rol[N];
int col[N];
int n;
bool flag[N][N];
//一个点对应两个坐标
struct node{
int first;
int second;
};
vector<node> res;
//移动方向
int dx[] = {0,0,1,-1};
int dy[] = {1,-1,0,0};
//判断是否到终点,需不需要继续深搜
bool check(int x, int y){
if(x==n&&y==n){
for(int i = 1; i <= n; i++){
if(col[i]!=0||rol[i]!=0)//箭没用完
return false;//不继续搜索了
}
//若路径符合要求,输出路径
for(int i = 0; i < res.size(); i++){
int x = res[i].first;
int y = res[i].second;
//计算出题目要求的坐标系对应的编号进行输出
int sum = n*(x-1)+(y-1);
cout<<sum<<" ";
}
return false;//不继续搜索了
}
return true;//继续深搜
}
//判断是否可以走,是否越界
bool pd(int x1,int y1){
//已经走过
if(flag[x1][y1]) return false;
if(x1<1||x1>n||y1<1||y1>n||col[x1]<=0||rol[y1]<=0)
return false;
return true;
}
void dfs(int x, int y){
if(!check(x,y)) return;
//4个方向
for(int i = 0; i < 4; i++){
int tx = dx[i] + x;
int ty = dy[i] + y;
if(!pd(tx,ty)) continue;
flag[tx][ty] = true;
//行的箭数对应列即rol --- ty
rol[ty]--;
col[tx]--;
res.push_back({tx,ty});
dfs(tx,ty);
//还原,方便回溯
res.pop_back();
flag[tx][ty] = false;
rol[ty]++;
col[tx]++;
}
}
int main(){
memset(flag,0,sizeof flag);
cin>>n;
for(int i = 1; i <= n; i++){
cin>>rol[i];
}
for(int i = 1; i <= n; i++){
cin>>col[i];
}
//起始点标记为走过
flag[1][1] = true;
//箭数--
rol[1]--;
col[1]--;
res.push_back({1,1});
dfs(1,1);
return 0;
}
路径之谜问题
于 2023-03-22 00:17:17 首次发布