Go: package main

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

var scanner = bufio.NewScanner(os.Stdin)
const INF = 1<<31

func main() {
	scanner.Scan()
	n, _ := strconv.Atoi(scanner.Text())
	arr := make([][]int, n)
	for i := range arr {
		arr[i] = make([]int, n)
	}
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			arr[i][j] = INF
		}
	}
	for i := 0; i < n; i++ {
		scanner.Scan()
		buf := strings.Split(scanner.Text(), " ")
		input := make([]int, len(buf))
		for j := range input {
			input[j], _ = strconv.Atoi(buf[j])
		}
		x, k := input[0]-1, input[1]
		for j := 0; j < k; j++ {
			y := input[j+2]-1
			arr[x][y] = 1
		}
	}
	for k := 0; k < n; k++ {
		arr[k][k] = 0
		for i := 0; i < n; i++ {
			if arr[i][k] >= INF {
				continue
			}
			for j := 0; j < n; j++ {
				if arr[k][j] >= INF {
					continue
				}
				arr[i][j] = min(arr[i][j], arr[i][k]+arr[k][j])
			}
		}
	}
	scanner.Scan()
	p, _ := strconv.Atoi(scanner.Text())
	for i := 0; i < p; i++ {
		scanner.Scan()
		buf := strings.Split(scanner.Text(), " ")
		input := make([]int, len(buf))
		for j := range input {
			input[j], _ = strconv.Atoi(buf[j])
		}
		s, d, v := input[0]-1, input[1]-1, input[2]
		if arr[s][d] < v {
			fmt.Println(arr[s][d]+1)
		} else {
			fmt.Println("NA")
		}
	}
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

Python: # -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0144

"""
import sys
from sys import stdin
input = stdin.readline
from enum import Enum


class Graph(object):
    """ single source shortest path """
    class Status(Enum):
        """ ?????????????¨??????¶??? """
        white = 1  # ????¨????
        gray = 2  # ?¨???????
        black = 3  #?¨???????

    def __init__(self, n, data):
        self.num_of_nodes = n+1
        self.color = [Graph.Status.white] * self.num_of_nodes  # ????????????????¨??????¶???
        self.M = [[float('inf')] * self.num_of_nodes for _ in range(self.num_of_nodes)]
        for i in range(self.num_of_nodes):
            self.M[i][i] = 0
        self._make_matrix(data)  # data????????????????????£??\??????(?????\?¶???¨???????????????????????§????????????)
        self.d = [float('inf')] * self.num_of_nodes  # ?§???????????????????(?????????)
        self.p = [-1] * self.num_of_nodes  # ????????????????????????????¨?????????????????????????

    def _make_matrix(self, data):
        for d in data:
            r = d[0]
            for t in d[2:]:
                self.M[r][t] = 1

    def dijkstra(self, start):
        self.d[start] = 0
        self.p[start] = -1
        while True:
            mincost = float('inf')
            # ??\??????????????§??????????????¨?????????????????????u???????????????
            for i in range(len(self.d)):
                if self.color[i] != Graph.Status.black and self.d[i] < mincost:  # S????±???????????????????S??¨??\?¶?????????????????????????????????????????°???????????????????
                    mincost = self.d[i]
                    u = i  # u??????????????????ID
            if mincost == float('inf'):
                break
            self.color[u] = Graph.Status.black  # ?????????u???S????±???????????????´???
            for v in range(len(self.d)):
                if self.color[v] != Graph.Status.black and self.M[u][v] != float('inf'):
                    # v????????????????????????????????°??????S???????????£???u????????????????????????????????????????????°??????????????±??§??´??°??????
                    if self.d[u] + self.M[u][v] < self.d[v]:
                        self.d[v] = self.d[u] + self.M[u][v]
                        self.p[v] = u
                        self.color[v] = Graph.Status.gray

    def warshallFloyd(self):
        for k in range(self.num_of_nodes):
            for i in range(self.num_of_nodes):
                for j in range(self.num_of_nodes):
                    if self.M[i][k] + self.M[k][j] < self.M[i][j]: 
                        self.M[i][j] = self.M[i][k] + self.M[k][j]


def main(args):
    n = int(input())
    network = []
    for _ in range(n):
        network.append([int(x) for x in input().split()])

    packets = []
    p = int(input())
    for _ in range(p):
        packets.append([int(x) for x in input().split()])

    g = Graph(n, network)
    g.warshallFloyd()

    for s, d, v in packets:
        if g.M[s][d] < v:
            print(g.M[s][d]+1)
        else:
            print('NA')



if __name__ == '__main__':
    main(sys.argv[1:])

Python: class Graph():
    from collections import namedtuple
    __Pair = namedtuple("Pair", "cost point")

    def __init__(self, element_count):
        self.__element_count = element_count
        self.__adjacency_iist = [[] for _ in range(element_count)]

    def get_path(self, begin_Point, end_point, cost):
        item = self.__Pair(cost, end_point)
        self.__adjacency_iist[begin_Point].append(item)

    def dijkstra(self, begin_Point):

        from sys import maxsize as MAX_VALUE
        from queue import PriorityQueue
        state_table = {"NotVisited": 0, "Stay": 1, "Visited": 2}

        # 初期化
        pq = PriorityQueue()
        cost_table = [MAX_VALUE for _ in range(self.__element_count)]
        visit_state = [state_table["NotVisited"]
                       for _ in range(self.__element_count)]

        # 処理
        cost_table[begin_Point] = 0
        pq.put_nowait(self.__Pair(0, begin_Point))

        while not pq.empty():

            min_item = pq.get_nowait()
            min_point, min_cost = min_item.point, min_item.cost

            visit_state[min_point] = state_table["Visited"]

            if min_cost <= cost_table[min_point]:

                for cost, point in self.__adjacency_iist[min_point]:
                    if visit_state[point] != state_table["Visited"]:

                        if cost_table[min_point] + cost < cost_table[point]:
                            cost_table[point] = cost_table[min_point] + cost
                            visit_state[point] = state_table["Stay"]
                            pq.put_nowait(self.__Pair(cost_table[point], point))

        return cost_table


router_count = int(input())

graph = Graph(router_count)

for _ in range(router_count):
    data = [int(item) for item in input().split(" ")]
    data[0] -= 1

    for lp in range(data[1]):
        graph.get_path(data[0], data[2 + lp] - 1, 1)

for _ in range(int(input())):

    sender, destination, ttl = [int(item) for item in input().split(" ")]

    costs = graph.dijkstra(sender - 1)
    cost = costs[destination - 1] + 1

    if cost <= ttl:
        print(cost)
    else:
        print("NA")