按照點從0到n-1dfs即可。
一開始我在想能不能按照連接的順序來dfs,後來看了別人的答案發現這樣複雜而且沒有必要。
#include <iostream>
#include <math.h>
#include <iomanip>
#include <string>
#include <cstdio>
#include <stdio.h>
#include <cstring>
#include <algorithm>
#include <queue>
#include <vector>
#define INF 0x3f3f3f3f
#define N 300
#define ll long long
using namespace std;
bool mp[N][N];
int num[N];
int t;
int n,p;
bool dfs(int x){
int i,j,k;
for(i=1;i<=3;i++){
for(j=0;j<x;j++){
if(num[j] == i && mp[j][x]){
break;
}
}
if(j != x){
continue;
}
num[x] = i;
if(x == n-1){
return 1;
}else{
if(dfs(x+1)){
return 1;
}
}
num[x] = 0;
}
return 0;
}
int main() {
int i,j,x,y;
scanf("%d",&t);
while (t>0)
{
t--;
memset(mp,0,sizeof(mp));
memset(num,0,sizeof(num));
scanf("%d",&n);
scanf("%d",&p);
for(i=0;i<p;i++){
scanf("%d%d",&x,&y);
mp[x][y] = mp[y][x] = 1;
}
if(dfs(0)){
printf("Y\n");
}else{
printf("N\n");
}
}
return 0;
}