public static void main(String[]  args) {
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
			int n = Integer.parseInt(in.readLine());    
			boolean[][] nabomatrise = new boolean[n][n];
			String naboRad;
			for(int i=0;i<n;i++){
				naboRad=in.readLine();
				for(int j=0;j<n;j++) 
					if(naboRad.charAt(j)=='1')nabomatrise[i][j]=true;
			}
			String linje = in.readLine();
			StringBuilder sb = new StringBuilder();
			int startnode= Integer.parseInt(linje);
			sb.append((subgraftetthet(nabomatrise, startnode)));
			linje=in.readLine();
			while(linje!=null && linje.length()>0){
				sb.append("\n");
				startnode= Integer.parseInt(linje);
				sb.append((subgraftetthet(nabomatrise, startnode)));
				linje=in.readLine();
			}
			System.out.println(sb);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}