// Arup Guha
// 2/1/2014
// Solution to COT 3100 Program #2: Fast Matrix Exponentiation

import java.util.*;

public class fastmatexpo {

	public static void main(String[] args) {

		Scanner stdin = new Scanner(System.in);
		int numCases = stdin.nextInt();

		// Process each case.
		for (int loop=1; loop<=numCases; loop++) {

			int n = stdin.nextInt();
			long exp = stdin.nextLong();
			long mod = stdin.nextLong();

			// Read in the matrix.
			long[][] mat = new long[n][n];
			for (int i=0; i<n; i++)
				for (int j=0; j<n; j++)
					mat[i][j] = stdin.nextLong();

			// Create the object, exponentiatie and print the result.
			Matrix m = new Matrix(mat);
			Matrix ans = m.modPow(exp, mod);
			System.out.println("Case "+loop);
			System.out.print(ans);
		}
	}
}
class Matrix {

	private long[][] mat;
	private int R;
	private int C;

	// Generates an identiy matrix of size N x N.
	public Matrix(int N) {
		R = N;
		C = N;
		mat = new long[N][N];
		for (int i=0; i<N; i++)
			mat[i][i] = 1;
	}

	// Generates a matrix equivalent to a.
	public Matrix(long[][] a) {
		R = a.length;
		C = a[0].length;
		mat = new long[R][C];
		for (int i=0; i<a.length; i++)
			for (int j=0; j<a[0].length; j++)
				mat[i][j] = a[i][j];
	}

	public Matrix multiply(Matrix m, long mod) {

		// Can't multiply these.
		if (this.C != m.R) return null;

		// Allocate the right amount of space.
		long[][] ans = new long[this.R][m.C];

		// This is how we multiply.
		for (int i=0; i<this.R; i++)
			for (int j=0; j<m.C; j++)
				for (int k=0; k<m.R; k++)
					ans[i][j] = (ans[i][j] + (this.mat[i][k]*m.mat[k][j]))%mod;

		return new Matrix(ans);
	}

	public Matrix modPow(long exp, long mod) {

		// Can't do this.
		if (R != C) return null;

		// Base cases.
		if (exp == 0L) return new Matrix(R);
		if (exp == 1L) return new Matrix(mat);

		// Time savings here - even exponent case.
		if (exp%2L == 0) {
			Matrix tmp = modPow(exp/2, mod);
			return tmp.multiply(tmp, mod);
		}

		// Usual recursive breakdown for odd case.
		else {
			Matrix tmp = modPow(exp-1, mod);
			return this.multiply(tmp, mod);
		}

	}

	// Just for testing purposes.
	public String toString() {

		String ans = "";
		for (int i=0; i<R; i++) {
			for (int j=0; j<C; j++)
				ans = ans + mat[i][j] + " ";
			ans = ans + "\n";
		}
		return ans;
	}
}