← Home
```go
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var sc *bufio.Scanner

func init() {
	sc = bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 0, 1<<20), 1<<20)
}

func nextInt() int {
	sc.Scan()
	x, _ := strconv.Atoi(sc.Text())
	return x
}

type DSU struct {
	parent []int
	diff   []int
	h      int
	ok     bool
}

func newDSU(n, h int) *DSU {
	d := &DSU{
		parent: make([]int, n),
		diff:   make([]int, n),
		h:      h,
		ok:     true,
	}
	for i := 0; i < n; i++ {
		d.parent[i] = i
	}
	return d
}

func (d *DSU) find(x int) int {
	if d.parent[x] != x {
		px := d.parent[x]
		root := d.find(px)
		d.diff[x] = (d.diff[x] + d.diff[px]) % d.h
		d.parent[x] = root
	}
	return d.parent[x]
}

func (d *DSU) union(u, v, w int) {
	if !d.ok {
		return
	}
	ru, rv := d.find(u), d.find(v)
	if ru == rv {
		diff := (d.diff[u] - d.diff[v] - w) % d.h
		if diff < 0 {
			diff += d.h
		}
		if diff != 0 {
			d.ok = false
		}
	} else {
		d.parent[ru] = rv
		diff := (w - d.diff[u] + d.diff[v]) % d.h
		if diff < 0 {
			diff += d.h
		}
		d.diff[ru] = diff
	}
}

func powMod(a, b, mod int64) int64 {
	res := int64(1)
	for b > 0 {
		if b&1 == 1 {
			res = (res * a) % mod
		}
		a = (a * a) % mod
		b >>= 1
	}
	return res
}

func main() {
	t := nextInt()
	const MOD int64 = 1000000007
	for ; t > 0; t-- {
		n := nextInt()
		m := nextInt()
		h := nextInt()
		if h == 1 {
			for i := 0; i < n; i++ {
				for j := 0; j < m; j++ {
					nextInt()
				}
			}
			fmt.Println(1)
			continue
		}
		dsu := newDSU(n+m, h)
		for i := 0; i < n; i++ {
			for j := 0; j < m; j++ {
				x := nextInt()
				if x == -1 {
					continue
				}
				dsu.union(i, n+j, x)
			}
		}
		if !dsu.ok {
			fmt.Println(0)
			continue
		}
		visited := make([]bool, n+m)
		comps := 0
		for i := 0; i < n+m; i++ {
			r := dsu.find(i)
			if !visited[r] {
				visited[r] = true
				comps++
			}
		}
		ans := powMod(int64(h%int(MOD)), int64(comps-1), MOD)
		fmt.Println(ans)
	}
}
```