//#pragma GCC optimize(2)
#include <bits/stdc++.h>
#define ull unsigned long long
#define int long long
using namespace std;
using ll=long long;
inline void read(int& a) {
int w=1;char c;a=0;
while((c=getchar())<'0'||c>'9')if(c=='-')w=-1;
do a=a*10+(c^48); while((c=getchar())>='0'&&c<='9');
a*=w;
}
void write(int x){
if(x<0)putchar('-'),x=-x;
if(x>9)write(x/10);
putchar(x%10+'0');
return ;
}
const int N=2e5+10;
int n,m,lei,ans;
struct node{
int u,v,w;
};
bool vis[N],f;
vector<int> E[N];
void bfs(){
memset(vis,0,sizeof vis);
f=0;
queue<int>que;
que.push(1);
vis[1]=1;
while(que.size()){
int now=que.front();
que.pop();
for(int i:E[now]){
if(i==n){f=1;}
if(!vis[i]){
vis[i]=1;
que.push(i);
}
}
}
}
signed main() {
read(n),read(m);
vector<node> e(m+10);
for(int i=1;i<=m;i++)read(e[i].u),read(e[i].v),read(e[i].w),lei^=e[i].w;
ans=lei;
memset(vis,0,sizeof vis);
f=0;
for(int i=1;i<=m;i++)E[e[i].u].push_back(e[i].v);
bfs();
if(!f and !vis[n]){cout<<-1;exit(0);}
for(int i=1;i<=n;i++)E[i].clear();
for(int wei=10;wei>=0;wei--){
if(ans&(1<<wei)){
int now=ans^(1LL<<wei);
for(int i=1;i<=m;i++)if((now^(e[i].w))==now)E[e[i].u].push_back(e[i].v);
bfs();
for(int i=1;i<=n;i++)E[i].clear();
if(f||vis[n])ans=now;}
}
write(ans);
return 0;
}
//
// ⠀⢸⣿⣿⣿⠀⣼⣿⣿⣦⡀
// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⠀⠀⠀ ⠀⢸⣿⣿⡟⢰⣿⣿⣿⠟⠁
// ⠀⠀⠀⠀⠀⠀⠀⢰⣿⠿⢿⣦⣀⠀⠘⠛⠛⠃⠸⠿⠟⣫⣴⣶⣾⡆
// ⠀⠀⠀⠀⠀⠀⠀⠸⣿⡀⠀⠉⢿⣦⡀⠀⠀⠀⠀⠀⠀ ⠛⠿⠿⣿⠃
// ⠀⠀⠀⠀⠀⠀⠀⠀⠙⢿⣦⠀⠀⠹⣿⣶⡾⠛⠛⢷⣦⣄⠀
// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣧⠀⠀⠈⠉⣀⡀⠀ ⠀⠙⢿⡇
// ⠀⠀⠀⠀⠀⠀⢀⣠⣴⡿⠟⠋⠀⠀⢠⣾⠟⠃⠀⠀⠀⢸⣿⡆
// ⠀⠀⠀⢀⣠⣶⡿⠛⠉⠀⠀⠀⠀⠀⣾⡇⠀⠀⠀⠀⠀⢸⣿⠇
// ⢀⣠⣾⠿⠛⠁⠀⠀⠀⠀⠀⠀⠀⢀⣼⣧⣀⠀⠀⠀⢀⣼⠇
// ⠈⠋⠁⠀⠀⠀⠀⠀⠀⠀⠀⢀⣴⡿⠋⠙⠛⠛⠛⠛⠛⠁
// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣾⡿⠋⠀
// ⠀⠀⠀⠀⠀⠀⠀⠀⢾⠿⠋⠀
样例1过不去,大佬求救