fn determinant(mut mat: Vec>, m: u64) -> u64 { let n = mat.len(); assert!(mat.iter().all(|mat| mat.len() == n)); let mut det = 1; let mut op = vec![]; enum Operation { Swap(usize), Sub(usize, u64), } for i in (0..n).rev() { if let Some(x) = mat.iter().position(|mat| mat[i] != 0) { if i != x { mat.swap(i, x); det = m - det; } let mut a = mat.pop().unwrap(); let mut key = a[i]; for (j, mat) in mat.iter().enumerate() { let mut val = mat[i]; while val > 0 { if val < key { op.push(Operation::Swap(j)); std::mem::swap(&mut val, &mut key); } let q = val / key; val -= q * key; op.push(Operation::Sub(j, q)); } } for op in op.drain(..) { match op { Operation::Swap(i) => { std::mem::swap(&mut a, &mut mat[i]); det = m - det; }, Operation::Sub(k, q) => { for (mat, a) in mat[k].iter_mut().zip(a.iter()).take(i + 1) { *mat = (*mat + (m - q) * *a) % m; } }, } } det = det * a[i] % m; } else { return 0; } } det % m } // ---------- begin scannner ---------- #[allow(dead_code)] mod scanner { use std::str::FromStr; pub struct Scanner<'a> { it: std::str::SplitWhitespace<'a>, } impl<'a> Scanner<'a> { pub fn new(s: &'a String) -> Scanner<'a> { Scanner { it: s.split_whitespace(), } } pub fn next(&mut self) -> T { self.it.next().unwrap().parse::().ok().unwrap() } pub fn next_bytes(&mut self) -> Vec { self.it.next().unwrap().bytes().collect() } pub fn next_chars(&mut self) -> Vec { self.it.next().unwrap().chars().collect() } pub fn next_vec(&mut self, len: usize) -> Vec { (0..len).map(|_| self.next()).collect() } } } // ---------- end scannner ---------- use std::io::Write; use std::collections::*; type Map = BTreeMap; type Set = BTreeSet; type Deque = VecDeque; fn main() { use std::io::Read; let mut s = String::new(); std::io::stdin().read_to_string(&mut s).unwrap(); let mut sc = scanner::Scanner::new(&s); let out = std::io::stdout(); let mut out = std::io::BufWriter::new(out.lock()); run(&mut sc, &mut out); } fn run(sc: &mut scanner::Scanner, out: &mut std::io::BufWriter) { let t: u32 = sc.next(); for _ in 0..t { let mut n: usize = sc.next(); let p: i64 = sc.next(); let mut a = (0..n).map(|_| sc.next_vec::(n)).collect::>(); let mut mul = 1; while let Some(x) = (0..(n * n)).find(|x| a[x / n][x % n] == -1) { let (i, j) = (x / n, x % n); let c = (0..n).filter(|k| a[i][*k] == -1).count(); let d = (0..n).filter(|k| a[*k][i] == -1).count(); for a in a.iter_mut() { a.remove(j); } a.remove(i); if c + d > 2 { mul = 0; } else { mul = p * (p - 1) / 2 % p * mul % p; } n -= 1; } let a = a.iter().map(|a| a.iter().map(|a| *a as u64).collect()).collect::>>(); let ans = mul as u64 * determinant(a, p as u64) % p as u64; writeln!(out, "{}", ans).ok(); } }