#include<iostream>
#include<cstring>
#include<queue>
#define MAX_N 110
bool A[MAX_N][MAX_N];
int rooter_num;
using namespace std;
int bfs(int,int);
int main()
{
  int n,startNode,goalNode,TTL;
  int r,k,t;
  memset(A,false,sizeof(A));
  cin>>rooter_num;
  for(int i=0;i<rooter_num;i++)
    {
      cin>>r>>k;
      for(int j=0;j<k;j++)
	{
	  cin>>t;
	  A[r][t]=true;
	}
    }
  for(int i=1;i<=rooter_num;i++)
    {
      for(int j=1;j<=rooter_num;j++)
	{
	  cout<<A[i][j];
	}
      cout<<endl;
    }
  
  cin>>n;
  for(int i=0;i<n;i++)
    {
      cin>>startNode>>goalNode>>TTL;
      int a=bfs(startNode,goalNode);
      if(a>TTL)cout<<"NA"<<endl;
      else cout<<a<<endl;
    }
  return 0;
}
int bfs(int startNode,int goalNode)
{
  queue<int>Q;
  int visited[rooter_num+1];
  memset(visited,false,sizeof(visited));
  int currentNode=startNode;
  
  Q.push(currentNode);
  visited[currentNode]=true;
  
  while(!Q.empty())
    {

      
      currentNode=Q.front();
      Q.pop();
      for(int nextNode=1;nextNode<=rooter_num;nextNode++)
	{

	  if(A[currentNode][nextNode]==false)continue;

	  if(nextNode==goalNode)return visited[currentNode]+1;
	  
	  if(visited[nextNode]==false)
	    {
	      visited[nextNode]=visited[currentNode]+1;
	      Q.push(nextNode);
	    }
	}
    }
  return MAX_N;
}



  