#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

struct UnionFind {
    vector<int> par;
    int cnt;
    UnionFind(int size_) : par(size_, -1), cnt(size_) {}
    void unite(int x, int y) {
        if ((x = find(x)) != (y = find(y))) {
            if (par[y] < par[x]) swap(x, y);
            par[x] += par[y]; par[y] = x; cnt--;
        }
    }
    bool same(int x, int y) { return find(x) == find(y); }
    int find(int x) { return par[x] < 0 ? x : par[x] = find(par[x]); }
    int size(int x) { return -par[find(x)]; }
    int size() { return cnt; }
};

#define int int64_t

struct Edge {
    int src, dst, weight;
    Edge(int s, int d, int w) : src(s), dst(d), weight(w) {}
};
using Edges = vector<Edge>;
using Graph = vector<Edges>;

int n, m;
Graph g;

bool check(int l, int r) {
    UnionFind uf(g.size());
    for (auto &es : g) {
        for (auto &e : es) {
            if (l <= e.weight && e.weight <= r) {
                uf.unite(e.src, e.dst);
            }
        }
    }
    return uf.size() == 1;
}

int solve() {
    int ans = 1e9;
    for (int i = 0; i <= 10000; ++i) {
        int lb = i - 1;
        int ub = 10001;
        while (lb + 1 < ub) {
            int mid = (ub + lb) / 2;
            if (check(i, mid)) {
                ub = mid;
            } else {
                lb = mid;
            }
        }
        if (check(i, ub)) {
            ans = min(ans, ub - i);
        }
    }
    return ans == 1e9 ? -1 : ans;
}

signed main() {
    while (cin >> n >> m && n) {
        g.assign(n, {});
        for (int i = 0; i < m; i++) {
            int a, b, w;
            cin >> a >> b >> w;
            --a, --b;
            g[a].emplace_back(a, b, w);
            g[b].emplace_back(b, a, w);
        }
        cout << solve() << endl;
    }
}