题目链接:https://pintia.cn/problem-sets/994805046380707840/problems/994805048175869952
分析
这道题可以采用dfs+剪枝。
#include<iostream>
#include<vector>
using namespace std;
#define N 20 + 5
int n;
int a[N][N],b[N],visited[N];
bool check()//判断后续的点是否与第一个点有联系,没有就直接返回
{
for(int i = 1; i <= n; i++)
if(!visited[i] && a[i][1]) return true;
return false;
}
bool dfs(int v,int m)
{
b[m] = v;
if(m == n) {
if(a[v][1]) {
for(int i = 1; i < n; i++)
printf("%d ",b[i]);
printf("%d\n",b[n]);
return true;//找到第一个就直接返回
}
return false;
}
if(!check()) return false;
for(int i = 1; i <= n; i++) {
if(a[v][i] == 1 && visited[i] == 0) {
visited[i] = 1;
if(dfs(i,m + 1)) return true;
visited[i] = 0;
}
}
return false;
}
int main()
{
scanf("%d",&n);
char c;
getchar();
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++) {
scanf("%c",&c);
if(c == 'W') a[i][j] = 1;
else if(c == 'L') a[j][i] = 1;
}
getchar();
}
visited[1] = 1;
if(!dfs(1,1)) printf("No Solution\n");//因为字典序要最小,如果存在,肯定以1开头
return 0;
}