Petya and Vasya are playing a game. Petya's got n non-transparent glasses, standing in a row. The glasses' positions are indexed with integers from 1 to n from left to right. Note that the positions are indexed but the glasses are not.First Petya puts a marble under the glass in position s. Then he performs some (possibly zero) shuffling operations. One shuffling operation means moving the glass from the first position to position p1, the glass from the second position to position p2 and so on. That is, a glass goes from position i to position pi. Consider all glasses are moving simultaneously during one shuffling operation. When the glasses are shuffled, the marble doesn't travel from one glass to another: it moves together with the glass it was initially been put in.After all shuffling operations Petya shows Vasya that the ball has moved to position t. Vasya's task is to say what minimum number of shuffling operations Petya has performed or determine that Petya has made a mistake and the marble could not have got from position s to position t.

The first line contains three integers: n, s, t (1 ≤ n ≤ 105; 1 ≤ s, t ≤ n) — the number of glasses, the ball's initial and final position. The second line contains n space-separated integers: p1, p2, ..., pn (1 ≤ pi ≤ n) — the shuffling operation parameters. It is guaranteed that all pi's are distinct. Note that s can equal t.

If the marble can move from position s to position t, then print on a single line a non-negative integer — the minimum number of shuffling operations, needed to get the marble to position t. If it is impossible, print number -1.

package main

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

func main() {
	var n,s,t int
	var c [100010]int
	input := bufio.NewScanner(os.Stdin)
    	input.Split(bufio.ScanWords)

	fmt.Scan(&n,&s,&t)
	for i:=1;i<=n;i++ {
		input.Scan()
       		aa, _ := strconv.Atoi(input.Text())
		c[i]=aa
		//fmt.Scan(&c[i])
	}
	ans:=0
	for ;s!=t&&ans<=n; ans++ {
		s=c[s]
	}
	if ans>n {
		fmt.Println("-1")
	} else {
		fmt.Println(ans)
	}
}

package main

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

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Split(bufio.ScanWords)
    var n,s,t int
    var p [100005]int
    fmt.Scan(&n,&s,&t)
    for i := 1; i <= n; i++ {
        scanner.Scan()
        p[i], _ = strconv.Atoi(scanner.Text())
    }
    f := make([]bool,n+1)
    ans := 0
    for s != t {
        f[s] = true
        if !f[p[s]] {
            s = p[s]
            ans++
        } else {
            break
        }
    }
    if s != t { fmt.Println(-1) } else { fmt.Println(ans) }
}

package main

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

func main() {
	get := wrapStdin()
	n, s, t := get.Int(), get.Int(), get.Int()
	if s == t {
		fmt.Println("0")
		return
	}

	v := get.Nint(n)

	for i := 1; i < n; i++ {
		s = v[s-1]
		if s == t {
			fmt.Println(i)
			return
		}
	}
	fmt.Println("-1")
}

type Input struct {
	*bufio.Scanner
}

func wrapStdin() Input {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	return Input{Scanner: sc}
}
func (in Input) Int() int {
	in.Scan()
	x, _ := strconv.Atoi(in.Text())
	return x
}
func (in Input) IntOk() (int, bool) {
	ok := in.Scan()
	x, _ := strconv.Atoi(in.Text())
	return x, ok
}
func (in Input) Nint(n int) []int {
	v := make([]int, n)
	for i := 0; i < n; i++ {
		v[i] = in.Int()
	}
	return v
}
func (in Input) Vint(v []int) bool {
	var ok bool
	for i := 0; i < len(v); i++ {
		v[i], ok = in.IntOk()
	}
	return ok
}


Polygon is not only the best platform for developing problems but also a square matrix with side $$$n$$$, initially filled with the character 0.On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly $$$2n$$$ cannons were placed.    Initial polygon for $$$n=4$$$. Cannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.More formally:   if a cannon stands in the row $$$i$$$, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell ($$$i, 1$$$) and ends in some cell ($$$i, j$$$);  if a cannon stands in the column $$$j$$$, above the first row, and shoots with a 1, then the 1 starts its flight from the cell ($$$1, j$$$) and ends in some cell ($$$i, j$$$). For example, consider the following sequence of shots:   1. Shoot the cannon in the row $$$2$$$.                         2. Shoot the cannon in the row $$$2$$$.                         3. Shoot the cannon in column $$$3$$$. You have a report from the military training on your desk. This report is a square matrix with side length $$$n$$$ consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?Each cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 0.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \le n \le 50$$$) — the size of the polygon. This is followed by $$$n$$$ lines of length $$$n$$$, consisting of 0 and 1 — the polygon matrix after the training. The total area of the matrices in all test cases in one test does not exceed $$$10^5$$$.

For each test case print:   YES if there is a sequence of shots leading to a given matrix;  NO if such a sequence does not exist.  The letters in the words YES and NO can be printed in any case.

NoteThe first test case was explained in the statement.The answer to the second test case is NO, since a 1 in a cell ($$$1, 1$$$) flying out of any cannon would continue its flight further.

package main
import (
	"fmt"
	"os"
	"strconv"
	"bufio"
)

func main() {
	for t := nextInt(); t != 0; t-- {
		n := nextInt()
		mat := make([][]bool, n)
		for i := range mat {
			mat[i] = make([]bool, n)
			s := next()
			for idx, v := range s {
				mat[i][idx] = v == '1'
			}
		}
		// algo
		res := true
		for i, row := range mat {
			if i == n-1 {
				continue
			}
			for j := range row {
				if j == n-1 {
					continue
				}
				if mat[i][j] && mat[i][j+1] == mat[i+1][j] && mat[i+1][j] == false {
					res = false
					break
				}
			}
			if !res {
				break
			}
		}
		// Print
		if res {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

// -*-*-*-*-*-*-*-*-
// * I/O utilities *
// -*-*-*-*-*-*-*-*-
func init() {
	sc.Split(bufio.ScanWords)
}
var sc = bufio.NewScanner(os.Stdin)

func next() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	a, _ := strconv.Atoi(next())
	return a
}

func nextInt64() int64 {
	a, _ := strconv.ParseInt(next(), 10, 64)
	return a
}

func nextFloat64() float64 {
	a, _ := strconv.ParseFloat(next(), 64)
	return a
}

func nextInts(n int) []int {
	ret := make([]int, n)
	for i := 0; i < n; i++ {
		ret[i] = nextInt()
	}
	return ret
}
func nextFloats(n int) []float64 {
	ret := make([]float64, n)
	for i := 0; i < n; i++ {
		ret[i] = nextFloat64()
	}
	return ret
}
func nextStrings(n int) []string {
	ret := make([]string, n)
	for i := 0; i < n; i++ {
		ret[i] = next()
	}
	return ret
}

func split(s string) []string {
	ret := make([]string, len([]rune(s)))
	for i, v := range []rune(s) {
		ret[i] = string(v)
	}
	return ret
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') && bs[x] != '-' {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}

func main() {
	reader := bufio.NewReader(os.Stdin)

	tc := readNum(reader)

	for tc > 0 {
		tc--
		n := readNum(reader)
		G := make([][]byte, n)

		for i := 0; i < n; i++ {
			G[i], _ = reader.ReadBytes('\n')
		}
		res := solve(n, G)

		if res {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

func solve(n int, G [][]byte) bool {
	dp := make([][]bool, n)

	for i := 0; i < n; i++ {
		dp[i] = make([]bool, n)
	}

	for i := 0; i < n; i++ {
		if G[i][n-1] == '1' {
			dp[i][n-1] = true
		}
		if G[n-1][i] == '1' {
			dp[n-1][i] = true
		}
	}

	for i := n - 2; i >= 0; i-- {
		for j := n - 2; j >= 0; j-- {
			if G[i][j] == '0' {
				continue
			}
			if !dp[i+1][j] && !dp[i][j+1] {
				return false
			}
			dp[i][j] = true
		}
	}

	return true
}

package main

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

func main() {
	s := NewScanner()
	t := s.NextInt()

Next:
	for i := 0; i < t; i++ {
		n := s.NextInt()

		m := make([][]int, n)
		for j := 0; j < n; j++ {
			m[j] = make([]int, n)
			s := s.NextString()
			for k, c := range strings.Split(s, "") {
				if c == "0" {
					m[j][k] = 0
				} else {
					m[j][k] = 1
				}
			}
		}

		for j := 0; j < n; j++ {
			for k := 0; k < n; k++ {
				if m[j][k] == 0 {
					continue
				}

				var good bool
				if j < n-1 {
					if m[j+1][k] == 1 {
						good = true
					}
				}

				if k < n-1 {
					if m[j][k+1] == 1 {
						good = true
					}
				}

				if !good && j != n-1 && k != n-1 {
					fmt.Println("NO")
					continue Next
				}
			}
		}

		fmt.Println("YES")
	}
}

type scanner struct {
	*bufio.Scanner
}

func NewScanner() *scanner {
	s := bufio.NewScanner(os.Stdin)
	s.Split(bufio.ScanWords)
	return &scanner{s}
}

func (s *scanner) NextInt() int {
	s.Scan()
	i, _ := strconv.Atoi(s.Text())
	return i
}

func (s *scanner) NextInt64() int64 {
	s.Scan()
	i, _ := strconv.ParseInt(s.Text(), 10, 64)
	return i
}

func (s *scanner) NextString() string {
	s.Scan()
	return s.Text()
}

// https://codeforces.com/contest/1355/problem/A
package main

import (
	"bufio"
	"fmt"
	"os"
	"io"
)

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)
var input io.Reader

func main() {
	var (
		T int
	)

	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input = bufio.NewReader(os.Stdin)
	fmt.Fscanln(input, &T)
	for i := 0; i < T; i++ {
		fmt.Println(solver())
	}
}
var (
	n int
	p []string
	good [][]bool
)

func solver() string {
	fmt.Fscanln(input, &n)
	p = make([]string, n)
	good = make([][]bool, n)
	for i := 0; i < n; i++ {
		good[i] = make([]bool, n)
		fmt.Fscanln(input, &p[i])
	}

	for i := 0; i < n; i++ {
		mark(n - 1, i)
		mark(i, n - 1)
	}

	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			if p[i][j] == '1' && !good[i][j] {
				return "NO"
			}
		}
	}

	return "YES"
}

func mark(i, j int) {
	if good[i][j] {
		return
	}
	if p[i][j] == '1' {
		good[i][j] = true
		if i > 0 {
			mark(i - 1, j)
		}
		if j > 0 {
			mark(i, j - 1)
		}
	}
}

// https://codeforces.com/contest/1355/problem/A
package main

import (
	"bufio"
	"fmt"
	"os"
	"io"
)

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)
var input io.Reader

func main() {
	var (
		T int
	)

	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input = bufio.NewReader(os.Stdin)
	fmt.Fscanln(input, &T)
	for i := 0; i < T; i++ {
		fmt.Println(solver())
	}
}
var (
	n int
	p []string
	good [][]bool
)

func solver() string {
	fmt.Fscanln(input, &n)
	p = make([]string, n)
	good = make([][]bool, n)
	for i := 0; i < n; i++ {
		good[i] = make([]bool, n)
		fmt.Fscanln(input, &p[i])
	}

	last := n - 1
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			if p[i][j] == '1' {
				if i == last || j == last {
					continue
				}
				if i < last  {
					if p[i + 1][j] == '1' {
						continue
					}
				}

				if j < last  {
					if p[i][j + 1] == '1' {
						continue
					}
				}

				return "NO"
			}
		}
	}

	return "YES"
}

package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"sort"
  "strings"
  "strconv"
  "math"
)

var reader = NewWordScanner(os.Stdin)
var writer = NewBufferedWriter(os.Stdout)

func main() {
	defer writer.Flush()
	t := reader.NextInt64()
	for ; t > 0; t-- {
		n:= reader.NextInt64()
		aa := make([][]int, n)
		for i:=range aa {
			aa[i]=make([]int, n)
		}

		for i := 0; i < len(aa); i++ {
			line:=reader.NextString();
			split:=strings.Split(line,"")
			for j:=0;j<len(split);j++{
				aa[i][j],_=strconv.Atoi(split[j])
			}
		}
		sol(aa)
	}
}

func sol(aa [][]int) {
	for i:=0;i<len(aa)-1;i++{
		for j:=0;j<len(aa)-1;j++{
			if(aa[i][j]==1){
				if(aa[i+1][j]==0 && aa[i][j+1]==0){
					writer.Printf("NO \n")
					return;
				}
			}
		}
	}
	writer.Printf("YES \n")

}

/*********************** I/O ***********************/

type BufferedWriter interface {
	Printf(format string, a ...interface{})
	Flush()
}

type writerImpl struct {
	*bufio.Writer
}

func NewBufferedWriter(writer io.Writer) BufferedWriter {
	return &writerImpl{Writer: bufio.NewWriter(writer)}
}

func (impl *writerImpl) Printf(f string, a ...interface{}) {
	fmt.Fprintf(impl.Writer, f, a...)
}

func (impl *writerImpl) Flush() {
	impl.Writer.Flush()
}

type WordScanner interface {
	NextInt() int
	NextInt64() int64
	NextString() string
}

type wordScannerImpl struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
	s := bufio.NewScanner(reader)
	s.Split(bufio.ScanWords)
	// adjust the following size as needed
	// 2 << 17 is good enough to scan strings of len 2*10^5
	// it could go as high as 2 << 26 before cf judge breaks
	size := 2 << 20
	buf := make([]byte, size)
	s.Buffer(buf, size)
	return &wordScannerImpl{Scanner: s}
}

func (impl *wordScannerImpl) NextInt() int {
	impl.Scan()
	bb := impl.Bytes()
	i := 0
	if bb[0] == '-' {
		for _, b := range bb[1:] {
			i *= 10
			i -= int(b - '0')
		}
		return i
	}
	for _, b := range bb {
		i *= 10
		i += int(b - '0')
	}
	return i
}

func (impl *wordScannerImpl) NextInt64() int64 {
	impl.Scan()
	bb := impl.Bytes()
	i := int64(0)
	if bb[0] == '-' {
		for _, b := range bb[1:] {
			i *= 10
			i -= int64(b - '0')
		}
		return i
	}
	for _, b := range bb {
		i *= 10
		i += int64(b - '0')
	}
	return i
}

func (impl *wordScannerImpl) NextString() string {
	impl.Scan()
	return impl.Text()
}
/*********************** Utils ***********************/

func S(v interface{}) string { return fmt.Sprintf("%v", v) }
func SArr(a []int) string {
	sb := strings.Builder{}
	sb.Grow(len(a) * 9)
	for i := range a {
		sb.WriteString(strconv.Itoa(a[i]) + " ")
	}
	return sb.String()
}
func SArr64(a []int64) string {
	sb := strings.Builder{}
	sb.Grow(len(a) * 9)
	for i := range a {
		sb.WriteString(strconv.FormatInt(a[i], 10) + " ")
	}
	return sb.String()
}
func MnMx(args ...int64) (int64, int64) {
	minVal, maxVal := int64(math.MaxInt64), int64(math.MinInt64)
	for _, v := range args {
		if v < minVal {
			minVal = v
		}
		if v > maxVal {
			maxVal = v
		}
	}
	return minVal, maxVal
}
func Mn(args ...int64) int64 { mn, _ := MnMx(args...); return mn }
func Mx(args ...int64) int64 { _, mx := MnMx(args...); return mx }
func LCM(a, b int64) int64   { return a / GCD(a, b) * b }
func GCD(a, b int64) int64 {
	if a == 0 {
		return b
	}
	return GCD(b%a, a)
}
func sortInt64Slice(a []int64) { sort.Slice(a, func(i, j int) bool { return a[i] < a[j] }) }
func abs(x int64) int64 {
	if x < 0 {
		return -x
	}
	return x
}

/*
URL:
https://codeforces.com/contest/1360/problem/E
*/

package main

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"math"
	"os"
	"strconv"
)

/********** FAU standard libraries **********/

//fmt.Sprintf("%b\n", 255) 	// binary expression

/********** I/O usage **********/

//str := ReadString()
//i := ReadInt()
//X := ReadIntSlice(n)
//S := ReadRuneSlice()
//a := ReadFloat64()
//A := ReadFloat64Slice(n)

//str := ZeroPaddingRuneSlice(num, 32)
//str := PrintIntsLine(X...)

/*******************************************************************/

const (
	// General purpose
	MOD          = 1000000000 + 7
	ALPHABET_NUM = 26
	INF_INT64    = math.MaxInt64
	INF_BIT60    = 1 << 60
	INF_INT32    = math.MaxInt32
	INF_BIT30    = 1 << 30
	NIL          = -1

	// for dijkstra, prim, and so on
	WHITE = 0
	GRAY  = 1
	BLACK = 2
)

func init() {
	// bufio.ScanWords <---> bufio.ScanLines
	ReadString = newReadString(os.Stdin, bufio.ScanWords)
	stdout = bufio.NewWriter(os.Stdout)
}

var (
	t int
	n int
	A [][]rune
)

func main() {
	t = ReadInt()
	for i := 0; i < t; i++ {
		n = ReadInt()

		A = [][]rune{}

		for j := 0; j < n; j++ {
			row := ReadRuneSlice()
			A = append(A, row)
		}

		solve(n, A)
	}
}

func solve(n int, A [][]rune) {
	// 右端を埋める
	for i := 0; i < n; i++ {
		A[i] = append(A[i], '1')
	}
	// 一番下を埋める
	row := []rune{}
	for i := 0; i < n+1; i++ {
		row = append(row, '1')
	}
	A = append(A, row)

	// for i := 0; i < n+1; i++ {
	// 	PrintfDebug("%v\n", string(A[i]))
	// }
	// PrintfDebug("\n")

	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			if A[i][j] == '1' {
				ok := A[i+1][j] == '1' || A[i][j+1] == '1'
				if !ok {
					fmt.Println("NO")
					return
				}
			}
		}
	}
	fmt.Println("YES")
}

/*******************************************************************/

/*********** I/O ***********/

var (
	// ReadString returns a WORD string.
	ReadString func() string
	stdout     *bufio.Writer
)

func newReadString(ior io.Reader, sf bufio.SplitFunc) func() string {
	r := bufio.NewScanner(ior)
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	r.Split(sf)

	return func() string {
		if !r.Scan() {
			panic("Scan failed")
		}
		return r.Text()
	}
}

// ReadInt returns an integer.
func ReadInt() int {
	return int(readInt64())
}
func ReadInt2() (int, int) {
	return int(readInt64()), int(readInt64())
}
func ReadInt3() (int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64())
}
func ReadInt4() (int, int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64()), int(readInt64())
}

// ReadInt64 returns as integer as int64.
func ReadInt64() int64 {
	return readInt64()
}
func ReadInt64_2() (int64, int64) {
	return readInt64(), readInt64()
}
func ReadInt64_3() (int64, int64, int64) {
	return readInt64(), readInt64(), readInt64()
}
func ReadInt64_4() (int64, int64, int64, int64) {
	return readInt64(), readInt64(), readInt64(), readInt64()
}

func readInt64() int64 {
	i, err := strconv.ParseInt(ReadString(), 0, 64)
	if err != nil {
		panic(err.Error())
	}
	return i
}

// ReadIntSlice returns an integer slice that has n integers.
func ReadIntSlice(n int) []int {
	b := make([]int, n)
	for i := 0; i < n; i++ {
		b[i] = ReadInt()
	}
	return b
}

// ReadInt64Slice returns as int64 slice that has n integers.
func ReadInt64Slice(n int) []int64 {
	b := make([]int64, n)
	for i := 0; i < n; i++ {
		b[i] = ReadInt64()
	}
	return b
}

// ReadFloat64 returns an float64.
func ReadFloat64() float64 {
	return float64(readFloat64())
}

func readFloat64() float64 {
	f, err := strconv.ParseFloat(ReadString(), 64)
	if err != nil {
		panic(err.Error())
	}
	return f
}

// ReadFloatSlice returns an float64 slice that has n float64.
func ReadFloat64Slice(n int) []float64 {
	b := make([]float64, n)
	for i := 0; i < n; i++ {
		b[i] = ReadFloat64()
	}
	return b
}

// ReadRuneSlice returns a rune slice.
func ReadRuneSlice() []rune {
	return []rune(ReadString())
}

/*********** Debugging ***********/

// ZeroPaddingRuneSlice returns binary expressions of integer n with zero padding.
// For debugging use.
func ZeroPaddingRuneSlice(n, digitsNum int) []rune {
	sn := fmt.Sprintf("%b", n)

	residualLength := digitsNum - len(sn)
	if residualLength <= 0 {
		return []rune(sn)
	}

	zeros := make([]rune, residualLength)
	for i := 0; i < len(zeros); i++ {
		zeros[i] = '0'
	}

	res := []rune{}
	res = append(res, zeros...)
	res = append(res, []rune(sn)...)

	return res
}

// Strtoi is a wrapper of strconv.Atoi().
// If strconv.Atoi() returns an error, Strtoi calls panic.
func Strtoi(s string) int {
	if i, err := strconv.Atoi(s); err != nil {
		panic(errors.New("[argument error]: Strtoi only accepts integer string"))
	} else {
		return i
	}
}

// PrintIntsLine returns integers string delimited by a space.
func PrintIntsLine(A ...int) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.Itoa(A[i])
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}

// PrintIntsLine returns integers string delimited by a space.
func PrintInts64Line(A ...int64) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.FormatInt(A[i], 10) // 64bit int version
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}

// PrintfDebug is wrapper of fmt.Fprintf(os.Stderr, format, a...)
func PrintfDebug(format string, a ...interface{}) {
	fmt.Fprintf(os.Stderr, format, a...)
}

// PrintfBufStdout is function for output strings to buffered os.Stdout.
// You may have to call stdout.Flush() finally.
func PrintfBufStdout(format string, a ...interface{}) {
	fmt.Fprintf(stdout, format, a...)
}

package main

import . "fmt"

// github.com/EndlessCheng/codeforces-go
func main() {
	var t, n int
o:
	for Scan(&t); t > 0; t-- {
		Scan(&n)
		a := make([][]byte, n)
		for i := range a {
			Scan(&a[i])
		}
		for i, s := range a[:n-1] {
			for j, b := range s[:n-1] {
				if b == '1' && a[i][j+1] == '0' && a[i+1][j] == '0' {
					Println("NO")
					continue o
				}
			}
		}
		Println("YES")
	}
}

package main

import (
	"bufio"
	. "fmt"
	"io"
	"os"
)

// github.com/EndlessCheng/codeforces-go
func run(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	var t, n int
o:
	for Fscan(in, &t); t > 0; t-- {
		Fscan(in, &n)
		a := make([][]byte, n)
		for i := range a {
			Fscan(in, &a[i])
		}
		vis := make([][]bool, n)
		for i := range vis {
			vis[i] = make([]bool, n)
		}
		var f func(i, j int)
		f = func(i, j int) {
			if a[i][j] != '1' || vis[i][j] {
				return
			}
			vis[i][j] = true
			if i > 0 {
				f(i-1, j)
			}
			if j > 0 {
				f(i, j-1)
			}
		}
		for j := 0; j < n; j++ {
			f(n-1, j)
		}
		for i := 0; i < n; i++ {
			f(i, n-1)
		}
		for i, row := range a {
			for j, v := range row {
				if v == '1' && !vis[i][j] {
					Fprintln(out, "NO")
					continue o
				}
			}
		}
		Fprintln(out, "YES")
	}
}

func main() { run(os.Stdin, os.Stdout) }

package main

import (
	"fmt"
)

var n int
var a []string
var vis [][]bool

func dfs(i, j int) {
    vis[i][j] = true
    if (i - 1 >= 0 && a[i - 1][j] == '1' && !vis[i - 1][j]) {
        dfs(i - 1, j)
    }
    if (j - 1 >= 0 && a[i][j - 1] == '1' && !vis[i][j - 1]) {
        dfs(i, j - 1)
    }
}

func main() {
	var t int
	fmt.Scanf("%d\n", &t)
	for tc := 0; tc < t; tc++ {
		fmt.Scanf("%d\n", &n)
		a = make([]string, n)
		for i := 0; i < n; i++ {
		    fmt.Scanf("%s\n", &a[i])
		}
		vis = make([][]bool, n)
		for i := 0; i < n; i++ {
		    vis[i] = make([]bool, n)
		}
		for i := 0; i < n; i++ {
		    if (a[i][n - 1] == '1' && !vis[i][n - 1]) {
		        dfs(i, n - 1)
		    }
		    if (a[n - 1][i] == '1' && !vis[n - 1][i]) {
		        dfs(n - 1, i)
		    }
		}
		flag := true
		for i := 0; flag && i < n; i++ {
		    for j := 0; flag && j < n; j++ {
		        if (a[i][j] == '1' && !vis[i][j]) {
		            flag = false;
		        }
		    }
		}
		if flag {
		    fmt.Println("YES")
		} else {
		    fmt.Println("NO")
		}
	}
}

package main

import (
	"bufio"
	. "fmt"
	"os"
)

var (
	inn = bufio.NewScanner(os.Stdin)
	// in  = bufio.NewReader(os.Stdin)
	out = bufio.NewWriter(os.Stdout)
)

func main() {
	defer out.Flush()
	inn.Split(bufio.ScanWords)
	for tt := rd(); tt > 0; tt-- {
		n := rd()
		a := make([]string, n)
		for i := 0; i < n; i++ {
			a[i] = rds()
		}
		for i := 0; i < n; i++ {
			for j := 0; j < n; j++ {
				if a[i][j] == '0' {
					continue
				}
				if i != n-1 && j != n-1 && a[i+1][j] == '0' && a[i][j+1] == '0' {
					Fprintln(out, "NO")
					goto next
				}
			}
		}
		Fprintln(out, "YES")
	next:
	}
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}
func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
func rd() (x int) {
	inn.Scan()
	data := inn.Bytes()
	f := 1
	if data[0] == '-' {
		f = -1
		data = data[1:]
	}
	for _, b := range data {
		x = x*10 + int(b&15)
	}
	return f * x
}
func rdll() (x int64) {
	inn.Scan()
	data := inn.Bytes()
	f := int64(1)
	if data[0] == '-' {
		f = -1
		data = data[1:]
	}
	for _, b := range data {
		x = x*10 + int64(b&15)
	}
	return f * x
}

func rds() string {
	inn.Scan()
	data := inn.Bytes()
	return string(data)
}

package main

import (
	"fmt"
)

func main(){
	var T int
	fmt.Scan(&T)
	for t := 0; t < T; t++ {
		var n int
		fmt.Scan(&n)
		G := make([]string, n)
		for i := 0; i < n; i++ {
			fmt.Scan(&G[i])
		}
		good := true
		for i := 0; i+1 < n; i++ {
			for j := 0; j+1 < n; j++ {
				if G[i][j] == '1' && G[i+1][j] == '0' && G[i][j+1] == '0' {
					good = false
				}
			}
		}
		ans := "NO"
		if good {
			ans = "YES"
		}
		fmt.Println(ans)
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	// DEBUG ONLY
	// f, _ := os.Open("data.txt")
	// scanner := bufio.NewScanner(f)

	scanner := bufio.NewScanner(os.Stdin)

	var nCount int
	scanner.Scan()

	fmt.Sscanf(scanner.Text(), "%d", &nCount)

	var n int

	for ; nCount > 0; nCount-- {
		scanner.Scan()
		fmt.Sscanf(scanner.Text(), "%d", &n)
		polygon := make([][]bool, n)

		// create empty polygon
		for i := 0; i < n; i++ {
			polygon[i] = make([]bool, n)
		}

		// read polygon
		for i := 0; i < n; i++ {
			scanner.Scan()
			line := scanner.Text()
			for j := 0; j < n; j++ {
				if line[j] == '1' {
					polygon[j][i] = true
				}
			}
		}

		// test polygon
		res := true
		for x := n - 2; (x >= 0) && res; x-- {
			for y := n - 2; y >= 0; y-- {
				if (polygon[x][y]) && (!polygon[x+1][y]) && (!polygon[x][y+1]) {
					res = false
					break
				}
			}
		}
		if res {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}

	}

}

package main

import (
	"bufio"
	"fmt"
	"io"
	"math"
	"os"
)

type BufferedWriter interface {
	Printf(format string, a ...interface{})
	Flush()
}

type writerImpl struct {
	*bufio.Writer
}

func NewBufferedWriter(writer io.Writer) BufferedWriter {
	return &writerImpl{Writer: bufio.NewWriter(writer)}
}

func (impl *writerImpl) Printf(f string, a ...interface{}) {
	fmt.Fprintf(impl.Writer, f, a...)
}

func (impl *writerImpl) Flush() {
	impl.Writer.Flush()
}

type WordScanner interface {
	NextInt64() int64
	NextUInt64() uint64
	NextString() string
}

type wordScannerImpl struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
	s := bufio.NewScanner(reader)
	s.Split(bufio.ScanWords)
	// adjust the following size as needed
	// 2 << 17 is good enough to scan strings of len 2*10^5
	// it could go as high as 2 << 26 before cf judge breaks
	size := 2 << 20
	buf := make([]byte, size)
	s.Buffer(buf, size)
	return &wordScannerImpl{Scanner: s}
}

func (impl *wordScannerImpl) NextInt64() int64 {
	impl.Scan()
	bb := impl.Bytes()
	i := int64(0)
	if bb[0] == '-' {
		for _, b := range bb[1:] {
			i *= 10
			i -= int64(b - '0')
		}
		return i
	}
	for _, b := range bb {
		i *= 10
		i += int64(b - '0')
	}
	return i
}

func (impl *wordScannerImpl) NextUInt64() uint64 {
	impl.Scan()
	bb := impl.Bytes()
	i := uint64(0)
	for _, b := range bb {
		i *= 10
		i += uint64(b - '0')
	}
	return i
}

func (impl *wordScannerImpl) NextString() string {
	impl.Scan()
	return impl.Text()
}

func gcd(a, b int64) int64 {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

func lcm(a, b int64) int64 {
	return a * b / gcd(a, b)
}

func abs(a int64) int64 {
	if a < 0 {
		return a * -1
	}
	return a
}

func min(a int64, rest ...int64) int64 {
	for _, r := range rest {
		if r < a {
			a = r
		}
	}
	return a
}

func max(a int64, rest ...int64) int64 {
	for _, r := range rest {
		if r > a {
			a = r
		}
	}
	return a
}

const (
	INF = math.MaxInt64
	MOD = 1e9 + 7
)

var reader = NewWordScanner(os.Stdin)
var writer = NewBufferedWriter(os.Stdout)

func main() {
	defer writer.Flush()
	t := reader.NextInt64()
	for ; t > 0; t-- {
		n := reader.NextInt64()
		a := make([]string, n)
		for i := range a {
			a[i] = reader.NextString()
		}
		writer.Printf("%s\n", sol(a))
	}
}

func sol(a []string) string {
	n := len(a)
	for i := range a {
		for j := range a[i] {
			b := a[i][j]
			if b == '1' && i != n-1 && j != n-1 {
				if a[i+1][j] == '0' && a[i][j+1] == '0' {
					return "NO"
				}
			}
		}
	}
	return "YES"
}

// https://codeforces.com/contest/1355/problem/A
package main

import (
	"bufio"
	"fmt"
	"os"
	"io"
)

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)
var input io.Reader

func main() {
	var (
		T int
	)

	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input = bufio.NewReader(os.Stdin)
	fmt.Fscanln(input, &T)
	for i := 0; i < T; i++ {
		fmt.Println(solver())
	}
}
var (
	n int
	p []string
	good [][]bool
)

func solver() string {
	fmt.Fscanln(input, &n)
	p = make([]string, n)
	good = make([][]bool, n)
	for i := 0; i < n; i++ {
		good[i] = make([]bool, n)
		fmt.Fscanln(input, &p[i])
	}

	last := n - 1
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			if p[i][j] == '1' {
				if i < last  {
					if p[i + 1][j] != '1' {
						return "NO"
					}
				}

				if j < last  {
					if p[i][j + 1] != '1' {
						return "NO"
					}
				}
			}
		}
	}

	return "YES"
}