package main

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

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

	var n, x, y int
	Fscan(in, &n)
	ends := make([][][2]int, n)
	for i := range ends {
		ends[i] = make([][2]int, n)
		for j := range ends[i] {
			Fscan(in, &x, &y)
			if x > 0 {
				ends[i][j] = [2]int{x - 1, y - 1}
			} else {
				ends[i][j] = [2]int{-1, -1}
			}
		}
	}

	ans := make([][]byte, n)
	for i := range ans {
		ans[i] = make([]byte, n)
	}
	valid := func(x, y int) bool { return x >= 0 && x < n && y >= 0 && y < n }
	dir4 := [4][2]int{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}
	const dirMark = "LURD"
	var tar [2]int
	var makePath func(x, y int)
	makePath = func(x, y int) {
		for i, d := range dir4 {
			if xx, yy := x+d[0], y+d[1]; valid(xx, yy) && ans[xx][yy] == 0 && ends[xx][yy] == tar {
				ans[xx][yy] = dirMark[i]
				makePath(xx, yy)
			}
		}
	}
	for i, row := range ends {
		for j, ed := range row {
			if ans[i][j] > 0 {
				continue
			}
			if x, y := ed[0], ed[1]; x == -1 {
				tar = [2]int{-1, -1}
				if valid(i, j+1) && ends[i][j+1] == tar {
					ans[i][j] = 'R'
					ans[i][j+1] = 'L'
					makePath(i, j)
					makePath(i, j+1)
				} else if valid(i+1, j) && ends[i+1][j] == tar {
					ans[i][j] = 'D'
					ans[i+1][j] = 'U'
					makePath(i, j)
					makePath(i+1, j)
				} else {
					Fprint(out, "INVALID")
					return
				}
			} else {
				if ans[x][y] > 0 || ends[x][y] != ed {
					Fprint(out, "INVALID")
					return
				}
				ans[x][y] = 'X'
				tar = ed
				makePath(x, y)
				if ans[i][j] == 0 {
					Fprint(out, "INVALID")
					return
				}
			}
		}
	}
	Fprintln(out, "VALID")
	for _, row := range ans {
		Fprintf(out, "%s\n", row)
	}
}

// 1 1 1 1 0 0 4 4 0 0 1 7 1 7
// 1 1 1 1 0 0 4 4 0 0 1 7 1 7
// 0 0 0 0 0 0 4 4 0 0 0 0 0 0
// 0 0 4 4 4 4 4 4 4 4 4 4 0 0
// 0 0 0 0 0 0 4 4 0 0 0 0 0 0
// 7 1 0 0 0 0 4 4 0 0 7 7 7 7
// 7 1 0 0 0 0 0 0 0 0 7 7 7 7

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

package main

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

var reader io.Reader
var scanner *bufio.Scanner

func Init(io io.Reader, max_token_size int) {
	reader = bufio.NewReader(io)
	scanner = bufio.NewScanner(reader)
	// max token size
	scanner.Split(bufio.ScanWords)
	scanner.Buffer([]byte{}, max_token_size)
}

func stderr(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
}

func die(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
	os.Exit(1)
}

func NextInt() int {
	bytes := NextBytes()
	i, err := Atoi(bytes)
	if err != nil {
		die(err)
	}
	return i
}
func NextInt64() int64 {
	bytes := NextBytes()
	i, err := Atoi64(bytes)
	if err != nil {
		die(err)
	}
	return i
}

func NextBytes() []byte {
	if !scanner.Scan() {
		die(scanner.Err())
	}
	bytes := scanner.Bytes()
	copied := make([]byte, len(bytes))
	copy(copied, bytes)
	return copied
}

func Atoi(b []byte) (int, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	n := 0
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func Atoi64(b []byte) (int64, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	var n int64
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int64(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func ExtendByteArray(a []byte, size int) []byte {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]byte, size-len(a))...)
	}
}

func ExtendIntArray(a []int, size int) []int {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]int, size-len(a))...)
	}
}

func reverseInts(a []int) {
	for l, r := 0, len(a)-1; l < r; l, r = l+1, r-1 {
		a[l], a[r] = a[r], a[l]
	}
}

func unique(a []int) int {
	newLen := 0
	n := len(a)
	for i := 0; i < n; i++ {
		if newLen == 0 || a[i] != a[newLen-1] {
			a[newLen] = a[i]
			newLen++
		}
	}
	return newLen
}

func main() {
	inf := os.Stdin
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	// inf, err := os.Open("a.in")
	// if err != nil {
	// 	die(err)
	// }
	// out, err := os.Create("a.out")
	// if err != nil {
	// 	die(err)
	// }
	// defer out.Close()
	Init(inf, 1000010)

	n := NextInt()

	x := make([][]int, n)
	y := make([][]int, n)
	a := make([][]byte, n)
	was := make([][]bool, n)
	q := make([][2]int, n*n)
	qt := 0
	qh := 0
	for i := 0; i < n; i++ {
		x[i] = make([]int, n)
		y[i] = make([]int, n)
		a[i] = make([]byte, n)
		was[i] = make([]bool, n)
		for j := 0; j < n; j++ {
			x[i][j] = NextInt() - 1
			y[i][j] = NextInt() - 1
			if x[i][j] == i && y[i][j] == j {
				q[qt][0] = i
				q[qt][1] = j
				a[i][j] = 'X'
				was[i][j] = true
				qt++
			}
		}
	}

	var step = []byte{
		'R',
		'L',
		'D',
		'U',
	}

	var ds = [][]int{
		{0, 1},
		{0, -1},
		{1, 0},
		{-1, 0},
	}

	for qh < qt {
		i := q[qh][0]
		j := q[qh][1]
		qh++

		for k := 0; k < 4; k++ {
			ni := i + ds[k][0]
			nj := j + ds[k][1]
			if ni < 0 || ni == n || nj < 0 || nj == n {
				continue
			}
			if was[ni][nj] {
				continue
			}
			if x[ni][nj] == x[i][j] && y[ni][nj] == y[i][j] {
				a[ni][nj] = step[k^1]
				was[ni][nj] = true
				q[qt][0] = ni
				q[qt][1] = nj
				qt++
			}
		}
	}

	// stderr("qt", qt, "n", n)
	placed := qt
	var dfs func(i, j int) bool
	dfs = func(i, j int) bool {
		was[i][j] = true
		for k := 0; k < 4; k++ {
			ni := i + ds[k][0]
			nj := j + ds[k][1]
			if ni < 0 || ni == n || nj < 0 || nj == n {
				continue
			}
			if x[ni][nj] != -2 {
				continue
			}
			if was[ni][nj] {
				placed++
				a[i][j] = step[k]
				return true
			}
			if dfs(ni, nj) {
				placed++
				a[i][j] = step[k]
				return true
			}
		}
		return false
	}

	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			if x[i][j] == -2 && !was[i][j] {
				// stderr("trying", i, j)
				if !dfs(i, j) {
					fmt.Fprintln(out, "INVALID")
					return
				}
			}
		}
	}

	// stderr("placed", placed)

	if placed != n*n {
		fmt.Fprintln(out, "INVALID")
		return
	}

	fmt.Fprintln(out, "VALID")
	for i := 0; i < n; i++ {
		fmt.Fprintln(out, string(a[i]))
	}

}

package main

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

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

	var n, x, y int
	Fscan(in, &n)
	ends := make([][][2]int, n)
	for i := range ends {
		ends[i] = make([][2]int, n)
		for j := range ends[i] {
			Fscan(in, &x, &y)
			if x > 0 {
				ends[i][j] = [2]int{x - 1, y - 1}
			} else {
				ends[i][j] = [2]int{-1, -1}
			}
		}
	}

	ans := make([][]byte, n)
	for i := range ans {
		ans[i] = make([]byte, n)
	}
	valid := func(x, y int) bool { return x >= 0 && x < n && y >= 0 && y < n }
	dir4 := [4][2]int{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}
	const dirMark = "LURD"
	var tar [2]int
	var makePath func(x, y int)
	makePath = func(x, y int) {
		for i, d := range dir4 {
			if xx, yy := x+d[0], y+d[1]; valid(xx, yy) && ans[xx][yy] == 0 && ends[xx][yy] == tar {
				ans[xx][yy] = dirMark[i]
				makePath(xx, yy)
			}
		}
	}
	for i, row := range ends {
		for j, ed := range row {
			if ans[i][j] > 0 {
				continue
			}
			if x, y := ed[0], ed[1]; x == -1 {
				tar = [2]int{-1, -1}
				if valid(i, j+1) && ends[i][j+1] == tar {
					ans[i][j] = 'R'
					ans[i][j+1] = 'L'
					makePath(i, j)
					makePath(i, j+1)
				} else if valid(i+1, j) && ends[i+1][j] == tar {
					ans[i][j] = 'D'
					ans[i+1][j] = 'U'
					makePath(i, j)
					makePath(i+1, j)
				} else {
					Fprint(out, "INVALID")
					return
				}
			} else {
				if ans[x][y] > 0 || ends[x][y] != ed {
					Fprint(out, "INVALID")
					return
				}
				ans[x][y] = 'X'
				tar = ed
				makePath(x, y)
				if ans[i][j] == 0 {
					Fprint(out, "INVALID")
					return
				}
			}
		}
	}
	Fprintln(out, "VALID")
	for _, row := range ans {
		Fprintf(out, "%s\n", row)
	}
}

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

package main

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

var reader io.Reader
var scanner *bufio.Scanner

func Init(io io.Reader, max_token_size int) {
	reader = bufio.NewReader(io)
	scanner = bufio.NewScanner(reader)
	// max token size
	scanner.Split(bufio.ScanWords)
	scanner.Buffer([]byte{}, max_token_size)
}

func stderr(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
}

func die(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
	os.Exit(1)
}

func NextInt() int {
	bytes := NextBytes()
	i, err := Atoi(bytes)
	if err != nil {
		die(err)
	}
	return i
}
func NextInt64() int64 {
	bytes := NextBytes()
	i, err := Atoi64(bytes)
	if err != nil {
		die(err)
	}
	return i
}

func NextBytes() []byte {
	if !scanner.Scan() {
		die(scanner.Err())
	}
	bytes := scanner.Bytes()
	copied := make([]byte, len(bytes))
	copy(copied, bytes)
	return copied
}

func Atoi(b []byte) (int, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	n := 0
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func Atoi64(b []byte) (int64, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	var n int64
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int64(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func ExtendByteArray(a []byte, size int) []byte {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]byte, size-len(a))...)
	}
}

func ExtendIntArray(a []int, size int) []int {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]int, size-len(a))...)
	}
}

func reverseInts(a []int) {
	for l, r := 0, len(a)-1; l < r; l, r = l+1, r-1 {
		a[l], a[r] = a[r], a[l]
	}
}

func unique(a []int) int {
	newLen := 0
	n := len(a)
	for i := 0; i < n; i++ {
		if newLen == 0 || a[i] != a[newLen-1] {
			a[newLen] = a[i]
			newLen++
		}
	}
	return newLen
}

func main() {
	inf := os.Stdin
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	// inf, err := os.Open("a.in")
	// if err != nil {
	// 	die(err)
	// }
	// out, err := os.Create("a.out")
	// if err != nil {
	// 	die(err)
	// }
	// defer out.Close()
	Init(inf, 1010)

	n := NextInt()

	x := make([][]int, n)
	y := make([][]int, n)
	a := make([][]byte, n)
	was := make([][]bool, n)
	q := make([][2]int, n*n)
	qt := 0
	qh := 0
	for i := 0; i < n; i++ {
		x[i] = make([]int, n)
		y[i] = make([]int, n)
		a[i] = make([]byte, n)
		was[i] = make([]bool, n)
		for j := 0; j < n; j++ {
			x[i][j] = NextInt() - 1
			y[i][j] = NextInt() - 1
			if x[i][j] == i && y[i][j] == j {
				q[qt][0] = i
				q[qt][1] = j
				a[i][j] = 'X'
				was[i][j] = true
				qt++
			}
		}
	}

	var step = []byte{
		'R',
		'L',
		'D',
		'U',
	}

	var ds = [][]int{
		{0, 1},
		{0, -1},
		{1, 0},
		{-1, 0},
	}

	for qh < qt {
		i := q[qh][0]
		j := q[qh][1]
		qh++

		for k := 0; k < 4; k++ {
			ni := i + ds[k][0]
			nj := j + ds[k][1]
			if ni < 0 || ni == n || nj < 0 || nj == n {
				continue
			}
			if was[ni][nj] {
				continue
			}
			if x[ni][nj] == x[i][j] && y[ni][nj] == y[i][j] {
				a[ni][nj] = step[k^1]
				was[ni][nj] = true
				q[qt][0] = ni
				q[qt][1] = nj
				qt++
			}
		}
	}

	// stderr("qt", qt, "n", n)
	placed := qt
	var dfs func(i, j int) bool
	dfs = func(i, j int) bool {
		was[i][j] = true
		for k := 0; k < 4; k++ {
			ni := i + ds[k][0]
			nj := j + ds[k][1]
			if ni < 0 || ni == n || nj < 0 || nj == n {
				continue
			}
			if x[ni][nj] != -2 {
				continue
			}
			if was[ni][nj] {
				placed++
				a[i][j] = step[k]
				return true
			}
			if dfs(ni, nj) {
				placed++
				a[i][j] = step[k]
				return true
			}
		}
		return false
	}

	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			if x[i][j] == -2 && !was[i][j] {
				// stderr("trying", i, j)
				if !dfs(i, j) {
					fmt.Fprintln(out, "INVALID")
					return
				}
			}
		}
	}

	// stderr("placed", placed)

	if placed != n*n {
		fmt.Fprintln(out, "INVALID")
		return
	}

	fmt.Fprintln(out, "VALID")
	for i := 0; i < n; i++ {
		fmt.Fprintln(out, string(a[i]))
	}

}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1316D(_r io.Reader, _w io.Writer) {
	in := bufio.NewScanner(_r)
	in.Split(bufio.ScanWords)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	read := func() (x int) {
		in.Scan()
		raw := in.Bytes()
		if raw[0] == '-' {
			return -1
		}
		for _, b := range raw {
			x = x*10 + int(b-'0')
		}
		return
	}

	n := read()
	ends := make([][][2]int, n)
	for i := range ends {
		ends[i] = make([][2]int, n)
		for j := range ends[i] {
			if x, y := read(), read(); x > 0 {
				ends[i][j] = [2]int{x - 1, y - 1}
			} else {
				ends[i][j] = [2]int{-1, -1}
			}
		}
	}

	ans := make([][]byte, n)
	for i := range ans {
		ans[i] = make([]byte, n)
	}
	valid := func(x, y int) bool { return x >= 0 && x < n && y >= 0 && y < n }
	dir4 := [4][2]int{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}
	const dirMark = "LURD"
	var tar [2]int
	var makePath func(x, y int)
	makePath = func(x, y int) {
		for i, d := range dir4 {
			if xx, yy := x+d[0], y+d[1]; valid(xx, yy) && ans[xx][yy] == 0 && ends[xx][yy] == tar {
				ans[xx][yy] = dirMark[i]
				makePath(xx, yy)
			}
		}
	}
	for i, row := range ends {
		for j, ed := range row {
			if ans[i][j] > 0 {
				continue
			}
			if x, y := ed[0], ed[1]; x == -1 {
				tar = [2]int{-1, -1}
				if valid(i, j+1) && ends[i][j+1] == tar {
					ans[i][j] = 'R'
					ans[i][j+1] = 'L'
					makePath(i, j)
					makePath(i, j+1)
				} else if valid(i+1, j) && ends[i+1][j] == tar {
					ans[i][j] = 'D'
					ans[i+1][j] = 'U'
					makePath(i, j)
					makePath(i+1, j)
				} else {
					Fprint(out, "INVALID")
					return
				}
			} else {
				if ans[x][y] > 0 || ends[x][y] != ed {
					Fprint(out, "INVALID")
					return
				}
				ans[x][y] = 'X'
				tar = ed
				makePath(x, y)
				if ans[i][j] == 0 {
					Fprint(out, "INVALID")
					return
				}
			}
		}
	}
	Fprintln(out, "VALID")
	for _, row := range ans {
		Fprintf(out, "%s\n", row)
	}
}

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

package main

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

var reader io.Reader
var scanner *bufio.Scanner

func Init(io io.Reader, max_token_size int) {
	reader = bufio.NewReader(io)
	scanner = bufio.NewScanner(reader)
	// max token size
	scanner.Split(bufio.ScanWords)
	scanner.Buffer([]byte{}, max_token_size)
}

func stderr(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
}

func die(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
	os.Exit(1)
}

func NextInt() int {
	bytes := NextBytes()
	i, err := Atoi(bytes)
	if err != nil {
		die(err)
	}
	return i
}
func NextInt64() int64 {
	bytes := NextBytes()
	i, err := Atoi64(bytes)
	if err != nil {
		die(err)
	}
	return i
}

func NextBytes() []byte {
	if !scanner.Scan() {
		die(scanner.Err())
	}
	bytes := scanner.Bytes()
	copied := make([]byte, len(bytes))
	copy(copied, bytes)
	return copied
}

func Atoi(b []byte) (int, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	n := 0
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func Atoi64(b []byte) (int64, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	var n int64
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int64(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func ExtendByteArray(a []byte, size int) []byte {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]byte, size-len(a))...)
	}
}

func ExtendIntArray(a []int, size int) []int {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]int, size-len(a))...)
	}
}

func reverseInts(a []int) {
	for l, r := 0, len(a)-1; l < r; l, r = l+1, r-1 {
		a[l], a[r] = a[r], a[l]
	}
}

func unique(a []int) int {
	newLen := 0
	n := len(a)
	for i := 0; i < n; i++ {
		if newLen == 0 || a[i] != a[newLen-1] {
			a[newLen] = a[i]
			newLen++
		}
	}
	return newLen
}

func main() {
	inf := os.Stdin
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	// inf, err := os.Open("a.in")
	// if err != nil {
	// 	die(err)
	// }
	// out, err := os.Create("a.out")
	// if err != nil {
	// 	die(err)
	// }
	// defer out.Close()
	Init(inf, 1000010)

	n := NextInt()

	x := make([][]int, n)
	y := make([][]int, n)
	a := make([][]byte, n)
	was := make([][]bool, n)
	q := make([][2]int, n*n)
	qt := 0
	qh := 0
	for i := 0; i < n; i++ {
		x[i] = make([]int, n)
		y[i] = make([]int, n)
		a[i] = make([]byte, n)
		was[i] = make([]bool, n)
		for j := 0; j < n; j++ {
			x[i][j] = NextInt() - 1
			y[i][j] = NextInt() - 1
			if x[i][j] == i && y[i][j] == j {
				q[qt][0] = i
				q[qt][1] = j
				a[i][j] = 'X'
				was[i][j] = true
				qt++
			}
		}
	}

	var step = []byte{
		'R',
		'L',
		'D',
		'U',
	}

	var ds = [][]int{
		{0, 1},
		{0, -1},
		{1, 0},
		{1, -1},
	}

	for qh < qt {
		i := q[qh][0]
		j := q[qh][1]
		qh++

		for k := 0; k < 4; k++ {
			ni := i + ds[k][0]
			nj := j + ds[k][1]
			if ni < 0 || ni == n || nj < 0 || nj == n {
				continue
			}
			if was[ni][nj] {
				continue
			}
			if x[ni][nj] == x[i][j] {
				a[ni][nj] = step[k^1]
				was[ni][nj] = true
				q[qt][0] = ni
				q[qt][1] = nj
				qt++
			}
		}
	}

	// stderr("qt", qt, "n", n)
	placed := qt
	var dfs func(i, j int) bool
	dfs = func(i, j int) bool {
		was[i][j] = true
		for k := 0; k < 4; k++ {
			ni := i + ds[k][0]
			nj := j + ds[k][1]
			if ni < 0 || ni == n || nj < 0 || nj == n {
				continue
			}
			if x[ni][nj] != -2 {
				continue
			}
			if was[ni][nj] {
				placed++
				a[i][j] = step[k]
				return true
			}
			if dfs(ni, nj) {
				placed++
				a[i][j] = step[k]
				return true
			}
		}
		return false
	}

	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			if x[i][j] == -2 && !was[i][j] {
				// stderr("trying", i, j)
				if !dfs(i, j) {
					fmt.Fprintln(out, "INVALID")
					return
				}
			}
		}
	}

	// stderr("placed", placed)

	if placed != n*n {
		fmt.Fprintln(out, "INVALID")
		return
	}

	fmt.Fprintln(out, "VALID")
	for i := 0; i < n; i++ {
		fmt.Fprintln(out, string(a[i]))
	}

}

package main

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

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

	var n, x, y int
	Fscan(in, &n)
	ends := make([][][2]int, n)
	for i := range ends {
		ends[i] = make([][2]int, n)
		for j := range ends[i] {
			Fscan(in, &x, &y)
			if x > 0 {
				ends[i][j] = [2]int{x - 1, y - 1}
			} else {
				ends[i][j] = [2]int{-1, -1}
			}
		}
	}

	ans := make([][]byte, n)
	for i := range ans {
		ans[i] = make([]byte, n)
	}
	valid := func(x, y int) bool { return x >= 0 && x < n && y >= 0 && y < n }
	dir4 := [4][2]int{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}
	const dirMark = "LURD"
	var tar [2]int
	var makePath func(x, y int)
	makePath = func(x, y int) {
		for i, d := range dir4 {
			if xx, yy := x+d[0], y+d[1]; valid(xx, yy) && ans[xx][yy] == 0 && ends[xx][yy] == tar {
				ans[xx][yy] = dirMark[i]
				makePath(xx, yy)
			}
		}
	}
	for i, row := range ends {
		for j, ed := range row {
			if ans[i][j] > 0 {
				continue
			}
			if x, y := ed[0], ed[1]; x == -1 {
				tar = [2]int{-1, -1}
				if valid(i, j+1) {
					ans[i][j] = 'R'
					ans[i][j+1] = 'L'
					makePath(i, j)
					makePath(i, j+1)
				} else if valid(i+1, j) {
					ans[i][j] = 'D'
					ans[i+1][j] = 'U'
					makePath(i, j)
					makePath(i+1, j)
				} else {
					Fprint(out, "INVALID")
					return
				}
			} else {
				if ends[x][y] != [2]int{x, y} {
					Fprint(out, "INVALID")
					return
				}
				ans[x][y] = 'X'
				tar = ed
				makePath(x, y)
				if ans[i][j] == 0 {
					Fprint(out, "INVALID")
					return
				}
			}
		}
	}
	Fprintln(out, "VALID")
	for _, row := range ans {
		Fprintf(out, "%s\n", row)
	}
}

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

package main

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

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

	var n, x, y int
	Fscan(in, &n)
	ends := make([][][2]int, n)
	for i := range ends {
		ends[i] = make([][2]int, n)
		for j := range ends[i] {
			Fscan(in, &x, &y)
			if x > 0 {
				ends[i][j] = [2]int{x - 1, y - 1}
			} else {
				ends[i][j] = [2]int{-1, -1}
			}
		}
	}

	ans := make([][]byte, n)
	for i := range ans {
		ans[i] = make([]byte, n)
	}
	valid := func(x, y int) bool { return x >= 0 && x < n && y >= 0 && y < n }
	dir4 := [4][2]int{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}
	const dirMark = "LURD"
	var tar [2]int
	var makePath func(x, y int)
	makePath = func(x, y int) {
		for i, d := range dir4 {
			if xx, yy := x+d[0], y+d[1]; valid(xx, yy) && ans[xx][yy] == 0 && ends[xx][yy] == tar {
				ans[xx][yy] = dirMark[i]
				makePath(xx, yy)
			}
		}
	}
	for i, row := range ends {
		for j, ed := range row {
			if ans[i][j] > 0 {
				continue
			}
			if x, y := ed[0], ed[1]; x == -1 {
				tar = [2]int{-1, -1}
				if valid(i, j+1) {
					ans[i][j] = 'R'
					ans[i][j+1] = 'L'
					makePath(i, j)
					makePath(i, j+1)
				} else if valid(i+1, j) {
					ans[i][j] = 'D'
					ans[i+1][j] = 'U'
					makePath(i, j)
					makePath(i+1, j)
				} else {
					Fprint(out, "INVALID")
					return
				}
			} else {
				if ans[x][y] > 0 || ends[x][y] != ed {
					Fprint(out, "INVALID")
					return
				}
				ans[x][y] = 'X'
				tar = ed
				makePath(x, y)
				if ans[i][j] == 0 {
					Fprint(out, "INVALID")
					return
				}
			}
		}
	}
	Fprintln(out, "VALID")
	for _, row := range ans {
		Fprintf(out, "%s\n", row)
	}
}

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

package main

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

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

	var n, x, y int
	Fscan(in, &n)
	ends := make([][][2]int, n)
	for i := range ends {
		ends[i] = make([][2]int, n)
		for j := range ends[i] {
			Fscan(in, &x, &y)
			if x > 0 {
				ends[i][j] = [2]int{x - 1, y - 1}
			} else {
				ends[i][j] = [2]int{-1, -1}
			}
		}
	}

	ans := make([][]byte, n)
	for i := range ans {
		ans[i] = make([]byte, n)
	}
	valid := func(x, y int) bool { return x >= 0 && x < n && y >= 0 && y < n }
	dir4 := [4][2]int{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}
	const dirMark = "LURD"
	var tar [2]int
	var makePath func(x, y int)
	makePath = func(x, y int) {
		for i, d := range dir4 {
			if xx, yy := x+d[0], y+d[1]; valid(xx, yy) && ans[xx][yy] == 0 && ends[xx][yy] == tar {
				ans[xx][yy] = dirMark[i]
				makePath(xx, yy)
			}
		}
	}
	for i, row := range ends {
		for j, ed := range row {
			if ans[i][j] > 0 {
				continue
			}
			if x, y := ed[0], ed[1]; x == -1 {
				tar = [2]int{-1, -1}
				if valid(i, j+1) {
					ans[i][j] = 'R'
					ans[i][j+1] = 'L'
					makePath(i, j)
					makePath(i, j+1)
				} else if valid(i+1, j) {
					ans[i][j] = 'D'
					ans[i+1][j] = 'U'
					makePath(i, j)
					makePath(i+1, j)
				} else {
					Fprint(out, "INVALID")
					return
				}
			} else {
				if ans[x][y] > 0 {
					Fprint(out, "INVALID")
					return
				}
				ans[x][y] = 'X'
				tar = ed
				makePath(x, y)
				if ans[i][j] == 0 {
					Fprint(out, "INVALID")
					return
				}
			}
		}
	}
	Fprintln(out, "VALID")
	for _, row := range ans {
		Fprintf(out, "%s\n", row)
	}
}

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

package main

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

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

	var n, x, y int
	Fscan(in, &n)
	ends := make([][][2]int, n)
	for i := range ends {
		ends[i] = make([][2]int, n)
		for j := range ends[i] {
			Fscan(in, &x, &y)
			if x > 0 {
				ends[i][j] = [2]int{x - 1, y - 1}
			} else {
				ends[i][j] = [2]int{-1, -1}
			}
		}
	}

	ans := make([][]byte, n)
	for i := range ans {
		ans[i] = make([]byte, n)
	}
	valid := func(x, y int) bool { return x >= 0 && x < n && y >= 0 && y < n }
	dir4 := [4][2]int{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}
	const dirMark = "LURD"
	var makeLoop func(x, y int)
	makeLoop = func(x, y int) {
		for i, d := range dir4 {
			if xx, yy := x+d[0], y+d[1]; valid(xx, yy) && ans[xx][yy] == 0 && ends[xx][yy][0] == -1 {
				ans[xx][yy] = dirMark[i]
				makeLoop(xx, yy)
			}
		}
	}
	var tar [2]int
	var makePath func(x, y int)
	makePath = func(x, y int) {
		for i, d := range dir4 {
			if xx, yy := x+d[0], y+d[1]; valid(xx, yy) && ans[xx][yy] == 0 && ends[xx][yy] == tar {
				ans[xx][yy] = dirMark[i]
				makePath(xx, yy)
			}
		}
	}
	for i, row := range ends {
		for j, ed := range row {
			if ans[i][j] > 0 {
				continue
			}
			if x, y := ed[0], ed[1]; x == -1 {
				if valid(i, j+1) {
					ans[i][j] = 'R'
					ans[i][j+1] = 'L'
					makeLoop(i, j)
					makeLoop(i, j+1)
				} else if valid(i+1, j) {
					ans[i][j] = 'D'
					ans[i+1][j] = 'U'
					makeLoop(i, j)
					makeLoop(i+1, j)
				} else {
					Fprint(out, "INVALID")
					return
				}
			} else {
				ans[x][y] = 'X'
				tar = ed
				makePath(x, y)
				if ans[i][j] == 0 {
					Fprint(out, "INVALID")
					return
				}
			}
		}
	}
	Fprintln(out, "VALID")
	for _, row := range ans {
		Fprintf(out, "%s\n", row)
	}
}

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


package main

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

var wr = bufio.NewWriter(os.Stdout)
var rd = bufio.NewScanner(os.Stdin)

func nextInt() int {
	rd.Scan()
	if n, err := strconv.Atoi(rd.Text()); err == nil {
		return n
	}
	return 0
}
func Max(a,b int)int{
	if a>b {
		return a
	}else{
		return b
	}
}
func main() {
	defer wr.Flush()
	rd.Buffer(make([]byte, 0), 1000000009)
	rd.Split(bufio.ScanWords)
	T := nextInt()
	for Case := 0; Case < T; Case++ {
		solve()
	}
}
func solve() {
	rd.Scan()
	s:=rd.Text()
	cnt1:=0
	for _,val:=range s{
		if val=='1'{
			cnt1++
		}
	}
	cnt0:=0
	res:=0
	for _,val:=range s{
		if val=='1'{
			cnt1--
		}
		if cnt1==0 && cnt0==0{
			res++
		}
		if(val=='0'){
			cnt0++
		}
	}
	fmt.Fprint(wr,res,"\n")
}

package main

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

var r = bufio.NewReader(os.Stdin)
var w = bufio.NewWriter(os.Stdout)

func slove() {
	defer w.Flush()
	var s string
	fmt.Fscan(r, &s)
	first_0, last_1 := -1, -1
	for i := range s {
		if s[i] == '0' && first_0 == -1 {
			first_0 = i
		} else if s[i] == '1' && first_0 != -1 {
			fmt.Fprintln(w, "1")
			return
		} else if s[i] == '1' {
			last_1 = i
		}
	}
	if first_0 != -1 && last_1 != -1 {
		fmt.Fprintln(w, first_0 - last_1 + 1)
	} else if first_0 == -1 && last_1 == -1 {
		fmt.Fprintln(w, len(s))
	} else if first_0 == -1 {
		fmt.Fprintln(w, len(s) - last_1)
	} else {
		fmt.Fprintln(w, first_0 + 1)
	}

}

func main() {
	var n int
	fmt.Fscan(r, &n)
	for i:=1;i<=n;i++ {
		slove()
	}
}

package main

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

func main() {
	in, out := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in, &t)

	for ii := 0; ii < t; ii++ {
		var s string
		fmt.Fscan(in, &s)
		o, z := 0, len(s)-1
		for i := 0; i < len(s); i++ {
			if z == len(s)-1 && s[i] == '0' {
				z = i
			}
			if s[i] == '1' {
				o = i
			}
		}
		fmt.Fprintln(out, z-o+1)
	}
}

package main
import("bufio";."fmt";"os";."strings")

// github.com/EndlessCheng/codeforces-go
func main() {
	in := bufio.NewReader(os.Stdin)
	T, s := 0, ""
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &s)
		i, j := LastIndex(s, "1"), Index(s, "0")
		if i < 0 {i = 0}
		if j < 0 {j = len(s) - 1}
		Println(j-i+1)
	}
}

package main

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

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

	T, s := 0, ""
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &s)
		i, j := strings.LastIndex(s, "1"), strings.Index(s, "0")
		if i < 0 {
			i = 0
		}
		if j < 0 {
			j = len(s) - 1
		}
		Fprintln(out, j-i+1)
	}
}

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

package main

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

/*
7
0
1
00
10
11
?
??
---
1
1
1
2
1
1
2
======
6
?????
111
11000
110?0?0
111??00?0
11??0
---
5
1
2
2
4
4
========
2
??0??
??0
---
3
3
++======
5
1???00
11???00
1???
1???0
11???00
---
5
5
4
5
5

*/

//goland:noinspection GoUnhandledErrorResult
func solve() {
	var s string
	scanf("%s\n", &s)

	if len(s) == 1 || s[0] == '0' {
		fmt.Fprintln(writer, 1)
		return
	}

	onlyQuestionMarks := true

	first0Idx := len(s)

	for i, r := range s {
		if r == '0' && first0Idx == len(s) {
			first0Idx = i
		}

		if r == '0' || r == '1' {
			onlyQuestionMarks = false
		}
	}

	if onlyQuestionMarks {
		fmt.Fprintln(writer, len(s))
		return
	}

	i := first0Idx - 1
	for ; i >= 0; i-- {
		if s[i] == '1' {
			break
		}
	}

	cnt := first0Idx - i
	if first0Idx != len(s) {
		cnt++
	}
	if i < 0 {
		cnt--
	}

	fmt.Fprintln(writer, cnt)
}

//goland:noinspection GoUnhandledErrorResult
func main() {
	defer writer.Flush()

	t := 1
	scanf("%d\n", &t)

	for ; t > 0; t-- {
		solve()
	}
}

const maxUint = ^uint(0)

//goland:noinspection GoUnusedConst
const minUint = 0
const maxInt = int(maxUint >> 1)

//goland:noinspection GoUnusedConst
const minInt = -maxInt - 1

var reader = bufio.NewReader(os.Stdin)
var writer = bufio.NewWriter(os.Stdout)

func scanf(f string, a ...interface{}) {
	if _, err := fmt.Fscanf(reader, f, a...); err != nil {
		panic(err)
	}
}

//goland:noinspection GoUnusedFunction
func reversed(s string) string {
	input := []rune(s)
	li := len(input)
	ret := make([]rune, li)
	for i, r := range input {
		ret[li-i-1] = r
	}
	return string(ret)
}

//goland:noinspection GoUnusedFunction
func divCeil(num, div int64) int64 {
	quot := num / div
	if num%div > 0 {
		quot++
	} else if num%div < 0 {
		quot--
	}
	return quot
}

//goland:noinspection GoUnusedFunction
func min(nums ...int) int {
	return nums[minIdx(nums...)]
}

//goland:noinspection GoUnusedFunction
func minIdx(nums ...int) int {
	minNumIdx := 0
	for i, num := range nums {
		if num < nums[minNumIdx] {
			minNumIdx = i
		}
	}

	return minNumIdx
}

//goland:noinspection GoUnusedFunction
func max(nums ...int) int {
	return nums[maxIdx(nums...)]
}

//goland:noinspection GoUnusedFunction
func maxIdx(nums ...int) int {
	maxNumIdx := 0
	for i, num := range nums {
		if num > nums[maxNumIdx] {
			maxNumIdx = i
		}
	}

	return maxNumIdx
}

//goland:noinspection GoUnusedFunction
func sum(nums ...int) (sum int) {
	for _, num := range nums {
		sum += num
	}
	return
}

//goland:noinspection GoUnusedFunction
func abs(num int) int {
	if num < 0 {
		return -num
	}
	return num
}

//goland:noinspection GoUnusedFunction
func isPrime(num int64) bool {
	if num == 2 || num == 3 {
		return true
	}

	if num <= 1 || num%2 == 0 || num%3 == 0 {
		return false
	}

	for i := int64(5); i*i <= num; i += 6 {
		if num%i == 0 || num%(i+2) == 0 {
			return false
		}
	}

	return true
}

//goland:noinspection GoUnusedFunction
func gcd(a, b int) int {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

//goland:noinspection GoUnusedFunction
func lcm(a, b int) int {
	return abs(a) / gcd(a, b) * abs(b)
}

// Examples:
//	digitAt(1234, -1) -> panic!
//	digitAt(1234, 0) -> 4
//	digitAt(1234, 1) -> 3
//	digitAt(1234, 2) -> 2
//	digitAt(1234, 3) -> 1
//	digitAt(1234, 4) -> panic!
//goland:noinspection GoUnusedFunction
func digitAt(num, pos int) int {
	if num == 0 {
		return 0
	}

	num = abs(num)

	lenNum := int(math.Log10(float64(num))) + 1
	if pos < 0 || pos >= lenNum {
		err := fmt.Sprintf("Out of bound access for digit. Position passed %d, number %d", pos, num)
		panic(err)
	}

	rem := num % int(math.Pow10(pos+1))
	return rem / int(math.Pow10(pos))
}

//goland:noinspection GoUnusedFunction
func factorize(num int64) []int64 {
	factors := make([]int64, 0)

	for ftr := int64(2); ftr*ftr <= num; ftr++ {
		for num%ftr == 0 {
			num /= ftr
			factors = append(factors, ftr)
		}
	}

	if num > 1 {
		factors = append(factors, num)
	}

	return factors
}

package main

import (
	"fmt"
)

func main() {
	var t int
	fmt.Scanln(&t)

	for i := 0; i < t; i++ {
		var s string
		fmt.Scanln(&s)

		fmt.Println(Soln(s))
	}
}

const (
	No  = '0'
	Yes = '1'
	CR  = '?'
)

func Soln(s string) int {
	n := len(s)

	fNo, lYes := -1, -1

	for i := 0; i < n; i++ {
		if s[i] == No {
			fNo = i
			break
		}
	}

	for i := n - 1; i >= 0; i-- {
		if s[i] == Yes {
			lYes = i
			break
		}
	}

	if fNo == -1 && lYes == -1 {
		return n
	}

	if fNo == -1 {
		return n - lYes
	}

	if lYes == -1 {
		return fNo + 1
	}

	return fNo - lYes + 1
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)
var wrtr = bufio.NewWriterSize(os.Stdout, 10_000_000)
var rdr = bufio.NewScanner(os.Stdin)
func gs() string  { rdr.Scan(); return rdr.Text() }
func gi() int     { i,e := strconv.Atoi(gs()); if e != nil {panic(e)}; return i }
func main() {
	//f1, _ := os.Create("cpu.prof"); pprof.StartCPUProfile(f1); defer pprof.StopCPUProfile()
	defer wrtr.Flush()
	infn := ""; if infn == "" && len(os.Args) > 1 {	infn = os.Args[1] }
	if infn != "" {	f, e := os.Open(infn); if e != nil { panic(e) }; rdr = bufio.NewScanner(f) }
	rdr.Split(bufio.ScanWords); rdr.Buffer(make([]byte,1024),1_000_000_000)
	// PROGRAM STARTS HERE
	T := gi()
	for tt:=1;tt<=T;tt++ {
		s := gs(); n := len(s)
		l1 := -1; f0 := -1
		// Can't have 101
		for i,c := range(s) { if c == '1' { l1 = i } else if c == '0' && f0 == -1 { f0 = i } }
		ans := 0
		if l1 == -1 && f0 == -1 {
			ans = n
		} else if l1 == -1 {
			ans = f0+1
		} else if f0 == -1 {
			ans = n - l1
		} else {
			ans = f0-l1+1
		}
		fmt.Fprintln(wrtr,ans)
	}
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()

	var T int
	fmt.Fscan(in, &T)
	for t := 0; t < T; t++ {
		var s string
		fmt.Fscan(in, &s)

		var x, y int
		for _, ch := range s {
			if ch == '0' {
				x++
			} else if ch == '1' {
				y++
			}
		}

		var tot int
		var a, b int
		for _, ch := range s {
			if ch == '1' {
				b++
				y--
				if y == 0 { // last 1 is a suspect
					tot++
				}
			} else if ch == '0' {
				a++
				x--
				if y == 0 && a == 1 { // first 0 is a suspect
					tot++
				}
			} else {
				if y == 0 && a == 0 {
					tot++
				}
			}
		}
		fmt.Fprintln(out, tot)
	}
}

package main

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

func main() {
	var (
		t int
	)

	reader := bufio.NewReader(os.Stdin)
	fmt.Scanf("%d\n", &t)

	for t > 0 {
		t--

		s, _ := reader.ReadString('\n')
		if s[len(s)-1] == 10 {
			s = s[:len(s)-1]
		}
		if s[len(s)-1] == 13 {
			s = s[:len(s)-1]
		}

		if len(s) == 1 {
  			fmt.Println(1)
  			continue
 		}

 		lindex := len(s) - 1
		rindex := 0
 		for i := 0; i < len(s); i++ {
  			if string(s[i]) == "0" {
   				lindex = i
   				break
  			}
		}

 		for i := len(s) - 1; i >= 0; i-- {
			if string(s[i]) == "1" {
				rindex = i
				break
			}
		}
                fmt.Println(math.Abs(float64(lindex-rindex)+1))
	}
}

package main

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

type Int int64

const (
	INF = 3e5 + 10
	L0  = Int(0)
	L1  = Int(1)
)

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()

	var t int
	Fscan(in, &t)

	for tt := 0; tt < t; tt++ {
		var s string
		Fscan(in, &s)

		f1 := 0
		for i, ch := range s {
			if ch == '1' {
				f1 = i
			}

		}

		l0 := len(s) - 1
		for i := len(s) - 1; i >= 0; i-- {
			if s[i] == '0' {
				l0 = i
			}
		}

		ans := (l0 - f1) + 1

		Fprintln(out, ans)

	}

}

func MakeGrid(h, w int) [][]Int {
	index := make([][]Int, h)
	data := make([]Int, h*w)
	for i := 0; i < h; i++ {
		index[i] = data[i*w : (i+1)*w]
	}
	return index
}

func Abs(x Int) Int {
	if x > 0 {
		return x
	}
	return -x
}

func Min(nums ...Int) Int {
	return nums[MinIdx(nums...)]
}

func MinIdx(nums ...Int) Int {
	maxNumIdx := L0
	for i, num := range nums {
		if num < nums[maxNumIdx] {
			maxNumIdx = Int(i)
		}
	}
	return maxNumIdx
}

func Max(nums ...Int) Int {
	return nums[MaxIdx(nums...)]
}

func MaxIdx(nums ...Int) Int {
	maxNumIdx := L0
	for i, num := range nums {
		if num > nums[maxNumIdx] {
			maxNumIdx = Int(i)
		}
	}
	return maxNumIdx
}

var (
	mod  Int
	fmod func(Int) Int = doNothing
)

// SetMod sets the mod. It must be called first.
func SetMod(newMod Int) {
	mod = newMod
	fmod = dynamicMod
}

func dynamicMod(m Int) Int {
	m %= mod
	if m < 0 {
		return m + mod
	}
	return m
}

func doNothing(m Int) Int {
	return m
}

// Mod returns m % mod.
func (m Int) Mod() Int {
	return fmod(m)
}

// Inv returns modular multiplicative inverse
func (m Int) Inv() Int {
	return m.Pow(Int(0).Sub(2))
}

// Pow returns m^n
func (m Int) Pow(n Int) Int {
	p := Int(1)
	for n > 0 {
		if n&1 == 1 {
			p.MulAs(m)
		}
		m.MulAs(m)
		n >>= 1
	}
	return p
}

// Add returns m+x
func (m Int) Add(x Int) Int {
	return (m + x).Mod()
}

// Sub returns m-x
func (m Int) Sub(x Int) Int {
	return (m - x).Mod()
}

// Mul returns m*x
func (m Int) Mul(x Int) Int {
	return (m * x).Mod()
}

// Div returns m/x
func (m Int) Div(x Int) Int {
	return m.Mul(x.Inv())
}

// AddAs assigns *m + x to *m and returns m
func (m *Int) AddAs(x Int) *Int {
	*m = m.Add(x)
	return m
}

// SubAs assigns *m - x to *m and returns m
func (m *Int) SubAs(x Int) *Int {
	*m = m.Sub(x)
	return m
}

// MulAs assigns *m * x to *m and returns m
func (m *Int) MulAs(x Int) *Int {
	*m = m.Mul(x)
	return m
}

// DivAs assigns *m / x to *m and returns m
func (m *Int) DivAs(x Int) *Int {
	*m = m.Div(x)
	return m
}

func (m *Int) MaxAs(x ...Int) *Int {
	*m = Max(append(x, *m)...)
	return m
}

func (m *Int) MinAs(x ...Int) *Int {
	*m = Min(append(x, *m)...)
	return m
}

package main

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

func main() {
	r, w := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer w.Flush()
	var n int
	Fscan(r, &n)
	t := 0
	var s string
	for t < n {
		t++
		Fscan(r, &s)
		if s[0] == '0'{
			Fprintln(w, 1)
			continue
		}
		left := 0
		right := len(s) - 1
		for i := range s{
			if s[i] == '1'{
				left = i
			}else if s[i] == '0' && right == len(s) - 1{
				right = i
			}
		}
		Fprintln(w, right - left + 1)
	}
}

package main

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

func main_div3_787_C() {
	_in, _out := os.Stdin, os.Stdout
	in, out := bufio.NewReader(_in), bufio.NewWriter(_out)
	defer out.Flush()
	var cas int = 1
	Fscan(in, &cas)
	var sol func()
	// Coding...
	sol = func() {
		var s string
		Fscan(in, &s)
		s = "1" + s + "0"
		i := len(s) - 1
		for i >= 0 && s[i] != '1' {
			i--
		}
		j := i
		for j < len(s) && s[j] != '0' {
			j++
		}
		ans := j - i + 1
		if i == 0 {
			ans--
		}
		if j == len(s)-1 {
			ans--
		}
		Fprintln(out, ans)
	}
	for i := 0; i < cas; i++ {
		sol()
	}
}

func main() {
	main_div3_787_C()
}

package main

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

/*
7
0
1
00
10
11
?
??
---
1
1
1
1
1
1
2
======
6
?????
111
11000
110?0?0
111??00?0
11??0
---
5
1
2
2
4
4
========
1
??0??
---
3
*/

//goland:noinspection GoUnhandledErrorResult
func solve() {
	var s string
	scanf("%s\n", &s)

	if len(s) == 1 || s[0] == '0' {
		fmt.Fprintln(writer, 1)
		return
	}

	allQuestions := true

	first0Idx := len(s)

	for i, r := range s {
		if r == '0' && first0Idx == len(s) {
			first0Idx = i
		}

		if r == '0' || r == '1' {
			allQuestions = false
		}
	}

	if allQuestions {
		fmt.Fprintln(writer, len(s))
		return
	}

	i := first0Idx - 1
	for ; i >= 0; i-- {
		if s[i] == '1' {
			break
		}
	}

	cnt := first0Idx - i
	if first0Idx != len(s) {
		cnt++
	}
	if i <= 0 {
		cnt--
	}

	fmt.Fprintln(writer, cnt)
}

//goland:noinspection GoUnhandledErrorResult
func main() {
	defer writer.Flush()

	t := 1
	scanf("%d\n", &t)

	for ; t > 0; t-- {
		solve()
	}
}

const maxUint = ^uint(0)

//goland:noinspection GoUnusedConst
const minUint = 0
const maxInt = int(maxUint >> 1)

//goland:noinspection GoUnusedConst
const minInt = -maxInt - 1

var reader = bufio.NewReader(os.Stdin)
var writer = bufio.NewWriter(os.Stdout)

func scanf(f string, a ...interface{}) {
	if _, err := fmt.Fscanf(reader, f, a...); err != nil {
		panic(err)
	}
}

//goland:noinspection GoUnusedFunction
func reversed(s string) string {
	input := []rune(s)
	li := len(input)
	ret := make([]rune, li)
	for i, r := range input {
		ret[li-i-1] = r
	}
	return string(ret)
}

//goland:noinspection GoUnusedFunction
func divCeil(num, div int64) int64 {
	quot := num / div
	if num%div > 0 {
		quot++
	} else if num%div < 0 {
		quot--
	}
	return quot
}

//goland:noinspection GoUnusedFunction
func min(nums ...int) int {
	return nums[minIdx(nums...)]
}

//goland:noinspection GoUnusedFunction
func minIdx(nums ...int) int {
	minNumIdx := 0
	for i, num := range nums {
		if num < nums[minNumIdx] {
			minNumIdx = i
		}
	}

	return minNumIdx
}

//goland:noinspection GoUnusedFunction
func max(nums ...int) int {
	return nums[maxIdx(nums...)]
}

//goland:noinspection GoUnusedFunction
func maxIdx(nums ...int) int {
	maxNumIdx := 0
	for i, num := range nums {
		if num > nums[maxNumIdx] {
			maxNumIdx = i
		}
	}

	return maxNumIdx
}

//goland:noinspection GoUnusedFunction
func sum(nums ...int) (sum int) {
	for _, num := range nums {
		sum += num
	}
	return
}

//goland:noinspection GoUnusedFunction
func abs(num int) int {
	if num < 0 {
		return -num
	}
	return num
}

//goland:noinspection GoUnusedFunction
func isPrime(num int64) bool {
	if num == 2 || num == 3 {
		return true
	}

	if num <= 1 || num%2 == 0 || num%3 == 0 {
		return false
	}

	for i := int64(5); i*i <= num; i += 6 {
		if num%i == 0 || num%(i+2) == 0 {
			return false
		}
	}

	return true
}

//goland:noinspection GoUnusedFunction
func gcd(a, b int) int {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

//goland:noinspection GoUnusedFunction
func lcm(a, b int) int {
	return abs(a) / gcd(a, b) * abs(b)
}

// Examples:
//	digitAt(1234, -1) -> panic!
//	digitAt(1234, 0) -> 4
//	digitAt(1234, 1) -> 3
//	digitAt(1234, 2) -> 2
//	digitAt(1234, 3) -> 1
//	digitAt(1234, 4) -> panic!
//goland:noinspection GoUnusedFunction
func digitAt(num, pos int) int {
	if num == 0 {
		return 0
	}

	num = abs(num)

	lenNum := int(math.Log10(float64(num))) + 1
	if pos < 0 || pos >= lenNum {
		err := fmt.Sprintf("Out of bound access for digit. Position passed %d, number %d", pos, num)
		panic(err)
	}

	rem := num % int(math.Pow10(pos+1))
	return rem / int(math.Pow10(pos))
}

//goland:noinspection GoUnusedFunction
func factorize(num int64) []int64 {
	factors := make([]int64, 0)

	for ftr := int64(2); ftr*ftr <= num; ftr++ {
		for num%ftr == 0 {
			num /= ftr
			factors = append(factors, ftr)
		}
	}

	if num > 1 {
		factors = append(factors, num)
	}

	return factors
}


package main

import (
	"fmt"
)

func main() {
	var n, m int
	fmt.Scan(&n, &m)

	board := make([]string, n, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&board[i])
	}

	for i := 0; i < n; i++ {
		line := []byte(board[i])
		for j := 0; j < m; j++ {
			if line[j] == '.' {
				if i%2 == 0 {
					if j%2 == 0 {
						line[j] = 'B'
					} else {
						line[j] = 'W'
					}
				} else {
					if j%2 == 0 {
						line[j] = 'W'
					} else {
						line[j] = 'B'
					}
				}
			}
		}

		fmt.Println(string(line))
	}
}

package main

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

var scanner = bufio.NewScanner(os.Stdin)
var writer = bufio.NewWriter(os.Stdout)

//Wrong
func main() {
	defer writer.Flush()
	scanner.Split(bufio.ScanWords)

	n, m := nextInt(), nextInt()

	for i := 0; i < n; i++ {
		line := next()

		for j := 0; j < m; j++ {
			if line[j] == '-' {
				print("-")
			} else if (i % 2 == 0 && j % 2 == 0) || (i % 2 == 1 && j % 2 == 1) {
				print("B")
			} else {
				print("W")
			}
		}

		println()
	}
}

func next() string {
	if !scanner.Scan() {
		panic("Scan error")
	}
	return scanner.Text()
}

func nextInt() int {
	n, err := strconv.Atoi(next())
	if err != nil {
		panic(err)
	}
	return n
}

func nextFloat() float64 {
	n, err := strconv.ParseFloat(next(), 64)
	if err != nil {
		panic(err)
	}
	return n
}

func println(a ...interface{}) {
	fmt.Fprintln(writer, a...)
}

func print(a ...interface{}) {
	fmt.Fprint(writer, a...)
}

func printf(format string, a ...interface{}) {
	fmt.Fprintf(writer, format, a...)
}

package main

import (
	"bufio"
	"bytes"
	"errors"
	"fmt"
	"io"
	"math/rand"
	"os"
	"strconv"
	"time"
	"unicode/utf8"
)

const ()

var ()

func solve() {
	/*n := readInt()
	firstName := make([]string, n)
	lastName := make([]string, n)
	for i := 0; i < n; i++ {
		firstName[i] = readString()
		lastName[i] = readString()
	}
	p := make([]int, n)
	for i := 0; i < n; i++ {
		p[i] = readInt() - 1
	}
	var last string
	for i := 0; i < n; i++ {
		if last > firstName[p[i]] && last > lastName[p[i]] {
			printString("NO\n")
			return
		}
		if firstName[p[i]] < lastName[p[i]] {
			if last < firstName[p[i]] {
				last = firstName[p[i]]
			} else {
				last = lastName[p[i]]
			}
		} else {
			if last < lastName[p[i]] {
				last = lastName[p[i]]
			} else {
				last = firstName[p[i]]
			}
		}
	}*/

	var n, m int
	var row string
	fmt.Scanf("%d%d\n", &n, &m)
	for i := 1; i <= n; i++ {
		fmt.Scanf("%s\n", &row)
		for j := 0; j < m; j++ {
			var cell = row[j]
			if row[j] == '.' {
				if (i+j)%2 == 0 {
					cell = 'B'
				} else {
					cell = 'W'
				}
			}
			fmt.Printf("%c", cell)
		}
		fmt.Println()
	}
}

// IO.

var (
	scanner *Scanner
	writer  *bufio.Writer
)

func main() {
	input := os.Stdin
	output := os.Stdout
	//	input, _ := os.Open("")
	//	output, _ := os.Create("")

	defer input.Close()
	defer output.Close()

	scanner = NewScanner(input)
	scanner.Split(bufio.ScanWords)

	writer = bufio.NewWriter(output)
	defer writer.Flush()

	rand.Seed(int64(time.Now().Nanosecond()))
	solve()
}

// Read.

func readString() string {
	scanner.Scan()
	ans := scanner.Text()
	return ans
}

func readLine() string {
	scanner.Split(bufio.ScanLines)
	defer scanner.Split(bufio.ScanWords)
	return readString()
}

func readInt() int {
	ans, _ := strconv.ParseInt(readString(), 10, 0)
	return int(ans)
}

func readInt64() int64 {
	ans, _ := strconv.ParseInt(readString(), 10, 64)
	return ans
}

func readFloat64() float64 {
	ans, _ := strconv.ParseFloat(readString(), 64)
	return ans
}

// Write.

func printString(value string) {
	writer.WriteString(value)
}

func printLine() {
	printString("\n")
}

func printSpace() {
	printString(" ")
}

func printInt(value int) {
	printString(strconv.FormatInt(int64(value), 10))
}

func printInt64(value int64) {
	printString(strconv.FormatInt(value, 10))
}

func printFloat64(value float64) {
	printString(strconv.FormatFloat(value, 'f', 20, 64))
}

// Tuple

type Tuple struct {
	a, b int
}

func (p Tuple) Equals(key Key) bool {
	return p.a == key.(Tuple).a
}

func (p Tuple) Less(key Key) bool {
	return p.a < key.(Tuple).a
}

type TupleSlice []Tuple

func (p TupleSlice) Len() int {
	return len(p)
}

func (p TupleSlice) Less(j, i int) bool {
	return p[j].a < p[i].a
}

func (p TupleSlice) Swap(j, i int) {
	p[j], p[i] = p[i], p[j]
}

// Min, max, abs.

func maxInt(a, b int) int {
	if a > b {
		return a
	} else {
		return b
	}
}

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

func absInt(a int) int {
	if a > 0 {
		return a
	} else {
		return -a
	}
}

func maxInt64(a, b int64) int64 {
	if a > b {
		return a
	} else {
		return b
	}
}

func minInt64(a, b int64) int64 {
	if a < b {
		return a
	} else {
		return b
	}
}

func absInt64(a int64) int64 {
	if a > 0 {
		return a
	} else {
		return -a
	}
}

func maxFloat64(a, b float64) float64 {
	if a > b {
		return a
	} else {
		return b
	}
}

func minFloat64(a, b float64) float64 {
	if a < b {
		return a
	} else {
		return b
	}
}

func absFloat64(a float64) float64 {
	if a > 0 {
		return a
	} else {
		return -a
	}
}

// Set Key interface implementations.

type Int int

func (p Int) Equals(key Key) bool {
	return int(p) == int(key.(Int))
}

func (p Int) Less(key Key) bool {
	return int(p) < int(key.(Int))
}

// Set.

type Key interface {
	Equals(key Key) bool
	Less(key Key) bool
}

type node struct {
	key   Key
	left  *node
	right *node
}

func newNode(key Key) *node {
	return &node{key, nil, nil}
}

type SplayTree struct {
	root *node
	tmp  *node
	len  int
}

func NewSplayTree() *SplayTree {
	return &SplayTree{nil, newNode(nil), 0}
}

func rotateLeft(x, p *node) {
	p.right = x.left
	x.left = p
}

func rotateRight(x, p *node) {
	p.left = x.right
	x.right = p
}

func (p *SplayTree) splay(x *node, key Key) *node {
	if x == nil {
		return nil
	}

	left := p.tmp
	right := p.tmp

	for {
		if key.Less(x.key) {
			y := x.left
			if y == nil {
				break
			}
			if key.Less(y.key) { // zig-zig
				rotateRight(y, x)
				x = y
				if x.left == nil {
					break
				}
			}
			// link right
			right.left = x
			right = x
			// move left
			x = x.left
		} else if x.key.Less(key) {
			y := x.right
			if y == nil {
				break
			}
			if y.key.Less(key) { // zig-zig
				rotateLeft(y, x)
				x = y
				if x.right == nil {
					break
				}
			}
			// link left
			left.right = x
			left = x
			// move right
			x = x.right
		} else {
			break
		}
	}

	left.right = x.left
	right.left = x.right
	x.left = p.tmp.right
	x.right = p.tmp.left

	return x
}

// left <= key < right
func (p *SplayTree) split(key Key) (left, right *node) {
	p.root = p.splay(p.root, key)
	if p.root.key.Equals(key) || p.root.key.Less(key) {
		right := p.root.right
		p.root.right = nil
		return p.root, right
	} else {
		left := p.root.left
		p.root.left = nil
		return left, p.root
	}
}

// keys from left tree must be less then keys from right tree
func (p *SplayTree) join(left, right *node) *node {
	if left == nil {
		return right
	} else if right == nil {
		return left
	}
	left = p.splay(left, right.key)
	left.right = right
	return left
}

type Set interface {
	Len() int
	Insert(key Key) error
	Find(key Key) bool
	Remove(key Key) error
}

func NewSet() Set {
	return Set(NewSplayTree())
}

func (p *SplayTree) Len() int {
	return p.len
}

func (p *SplayTree) Insert(key Key) error {
	if p.root == nil {
		p.root = newNode(key)
		p.len++
	} else {
		p.root = p.splay(p.root, key)
		if p.root.key.Equals(key) {
			return errors.New("Such key already exists")
		} else {
			left, right := p.split(key)
			p.root = newNode(key)
			p.root.left = left
			p.root.right = right
			p.len++
		}
	}
	return nil
}

func (p *SplayTree) Find(key Key) bool {
	if p.root == nil {
		return false
	}
	p.root = p.splay(p.root, key)
	return p.root.key.Equals(key)
}

func (p *SplayTree) Remove(key Key) error {
	p.root = p.splay(p.root, key)
	if p.root == nil || !p.root.key.Equals(key) {
		return errors.New("Such key doesn't exist")
	}
	p.root = p.join(p.split(key))
	return nil
}

// Copied scan.go
// Scanner provides a convenient interface for reading data such as
// a file of newline-delimited lines of text. Successive calls to
// the Scan method will step through the 'tokens' of a file, skipping
// the bytes between the tokens. The specification of a token is
// defined by a split function of type SplitFunc; the default split
// function breaks the input into lines with line termination stripped. Split
// functions are defined in this package for scanning a file into
// lines, bytes, UTF-8-encoded runes, and space-delimited words. The
// client may instead provide a custom split function.
//
// Scanning stops unrecoverably at EOF, the first I/O error, or a token too
// large to fit in the buffer. When a scan stops, the reader may have
// advanced arbitrarily far past the last token. Programs that need more
// control over error handling or large tokens, or must run sequential scans
// on a reader, should use bufio.Reader instead.
//
type Scanner struct {
	r            io.Reader // The reader provided by the client.
	split        SplitFunc // The function to split the tokens.
	maxTokenSize int       // Maximum size of a token; modified by tests.
	token        []byte    // Last token returned by split.
	buf          []byte    // Buffer used as argument to split.
	start        int       // First non-processed byte in buf.
	end          int       // End of data in buf.
	err          error     // Sticky error.
}

// SplitFunc is the signature of the split function used to tokenize the
// input. The arguments are an initial substring of the remaining unprocessed
// data and a flag, atEOF, that reports whether the Reader has no more data
// to give. The return values are the number of bytes to advance the input
// and the next token to return to the user, plus an error, if any. If the
// data does not yet hold a complete token, for instance if it has no newline
// while scanning lines, SplitFunc can return (0, nil, nil) to signal the
// Scanner to read more data into the slice and try again with a longer slice
// starting at the same point in the input.
//
// If the returned error is non-nil, scanning stops and the error
// is returned to the client.
//
// The function is never called with an empty data slice unless atEOF
// is true. If atEOF is true, however, data may be non-empty and,
// as always, holds unprocessed text.
type SplitFunc func(data []byte, atEOF bool) (advance int, token []byte, err error)

// Errors returned by Scanner.
var (
	ErrTooLong         = errors.New("bufio.Scanner: token too long")
	ErrNegativeAdvance = errors.New("bufio.Scanner: SplitFunc returns negative advance count")
	ErrAdvanceTooFar   = errors.New("bufio.Scanner: SplitFunc returns advance count beyond input")
)

const (
	// Maximum size used to buffer a token. The actual maximum token size
	// may be smaller as the buffer may need to include, for instance, a newline.
	MaxScanTokenSize = 1 << 20
)

// NewScanner returns a new Scanner to read from r.
// The split function defaults to ScanLines.
func NewScanner(r io.Reader) *Scanner {
	return &Scanner{
		r:            r,
		split:        ScanLines,
		maxTokenSize: MaxScanTokenSize,
		buf:          make([]byte, 4096), // Plausible starting size; needn't be large.
	}
}

// Err returns the first non-EOF error that was encountered by the Scanner.
func (s *Scanner) Err() error {
	if s.err == io.EOF {
		return nil
	}
	return s.err
}

// Bytes returns the most recent token generated by a call to Scan.
// The underlying array may point to data that will be overwritten
// by a subsequent call to Scan. It does no allocation.
func (s *Scanner) Bytes() []byte {
	return s.token
}

// Text returns the most recent token generated by a call to Scan
// as a newly allocated string holding its bytes.
func (s *Scanner) Text() string {
	return string(s.token)
}

// Scan advances the Scanner to the next token, which will then be
// available through the Bytes or Text method. It returns false when the
// scan stops, either by reaching the end of the input or an error.
// After Scan returns false, the Err method will return any error that
// occurred during scanning, except that if it was io.EOF, Err
// will return nil.
func (s *Scanner) Scan() bool {
	// Loop until we have a token.
	for {
		// See if we can get a token with what we already have.
		if s.end > s.start {
			advance, token, err := s.split(s.buf[s.start:s.end], s.err != nil)
			if err != nil {
				s.setErr(err)
				return false
			}
			if !s.advance(advance) {
				return false
			}
			s.token = token
			if token != nil {
				return true
			}
		}
		// We cannot generate a token with what we are holding.
		// If we've already hit EOF or an I/O error, we are done.
		if s.err != nil {
			// Shut it down.
			s.start = 0
			s.end = 0
			return false
		}
		// Must read more data.
		// First, shift data to beginning of buffer if there's lots of empty space
		// or space is neded.
		if s.start > 0 && (s.end == len(s.buf) || s.start > len(s.buf)/2) {
			copy(s.buf, s.buf[s.start:s.end])
			s.end -= s.start
			s.start = 0
		}
		// Is the buffer full? If so, resize.
		if s.end == len(s.buf) {
			if len(s.buf) >= s.maxTokenSize {
				s.setErr(ErrTooLong)
				return false
			}
			newSize := len(s.buf) * 2
			if newSize > s.maxTokenSize {
				newSize = s.maxTokenSize
			}
			newBuf := make([]byte, newSize)
			copy(newBuf, s.buf[s.start:s.end])
			s.buf = newBuf
			s.end -= s.start
			s.start = 0
			continue
		}
		// Finally we can read some input. Make sure we don't get stuck with
		// a misbehaving Reader. Officially we don't need to do this, but let's
		// be extra careful: Scanner is for safe, simple jobs.
		for loop := 0; ; {
			n, err := s.r.Read(s.buf[s.end:len(s.buf)])
			s.end += n
			if err != nil {
				s.setErr(err)
				break
			}
			if n > 0 {
				break
			}
			loop++
			if loop > 100 {
				s.setErr(io.ErrNoProgress)
				break
			}
		}
	}
}

// advance consumes n bytes of the buffer. It reports whether the advance was legal.
func (s *Scanner) advance(n int) bool {
	if n < 0 {
		s.setErr(ErrNegativeAdvance)
		return false
	}
	if n > s.end-s.start {
		s.setErr(ErrAdvanceTooFar)
		return false
	}
	s.start += n
	return true
}

// setErr records the first error encountered.
func (s *Scanner) setErr(err error) {
	if s.err == nil || s.err == io.EOF {
		s.err = err
	}
}

// Split sets the split function for the Scanner. If called, it must be
// called before Scan. The default split function is ScanLines.
func (s *Scanner) Split(split SplitFunc) {
	s.split = split
}

// Split functions

// ScanBytes is a split function for a Scanner that returns each byte as a token.
func ScanBytes(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	return 1, data[0:1], nil
}

var errorRune = []byte(string(utf8.RuneError))

// ScanRunes is a split function for a Scanner that returns each
// UTF-8-encoded rune as a token. The sequence of runes returned is
// equivalent to that from a range loop over the input as a string, which
// means that erroneous UTF-8 encodings translate to U+FFFD = "\xef\xbf\xbd".
// Because of the Scan interface, this makes it impossible for the client to
// distinguish correctly encoded replacement runes from encoding errors.
func ScanRunes(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}

	// Fast path 1: ASCII.
	if data[0] < utf8.RuneSelf {
		return 1, data[0:1], nil
	}

	// Fast path 2: Correct UTF-8 decode without error.
	_, width := utf8.DecodeRune(data)
	if width > 1 {
		// It's a valid encoding. Width cannot be one for a correctly encoded
		// non-ASCII rune.
		return width, data[0:width], nil
	}

	// We know it's an error: we have width==1 and implicitly r==utf8.RuneError.
	// Is the error because there wasn't a full rune to be decoded?
	// FullRune distinguishes correctly between erroneous and incomplete encodings.
	if !atEOF && !utf8.FullRune(data) {
		// Incomplete; get more bytes.
		return 0, nil, nil
	}

	// We have a real UTF-8 encoding error. Return a properly encoded error rune
	// but advance only one byte. This matches the behavior of a range loop over
	// an incorrectly encoded string.
	return 1, errorRune, nil
}

// dropCR drops a terminal \r from the data.
func dropCR(data []byte) []byte {
	if len(data) > 0 && data[len(data)-1] == '\r' {
		return data[0 : len(data)-1]
	}
	return data
}

// ScanLines is a split function for a Scanner that returns each line of
// text, stripped of any trailing end-of-line marker. The returned line may
// be empty. The end-of-line marker is one optional carriage return followed
// by one mandatory newline. In regular expression notation, it is `\r?\n`.
// The last non-empty line of input will be returned even if it has no
// newline.
func ScanLines(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	if i := bytes.IndexByte(data, '\n'); i >= 0 {
		// We have a full newline-terminated line.
		return i + 1, dropCR(data[0:i]), nil
	}
	// If we're at EOF, we have a final, non-terminated line. Return it.
	if atEOF {
		return len(data), dropCR(data), nil
	}
	// Request more data.
	return 0, nil, nil
}

// isSpace reports whether the character is a Unicode white space character.
// We avoid dependency on the unicode package, but check validity of the implementation
// in the tests.
func isSpace(r rune) bool {
	if r <= '\u00FF' {
		// Obvious ASCII ones: \t through \r plus space. Plus two Latin-1 oddballs.
		switch r {
		case ' ', '\t', '\n', '\v', '\f', '\r':
			return true
		case '\u0085', '\u00A0':
			return true
		}
		return false
	}
	// High-valued ones.
	if '\u2000' <= r && r <= '\u200a' {
		return true
	}
	switch r {
	case '\u1680', '\u180e', '\u2028', '\u2029', '\u202f', '\u205f', '\u3000':
		return true
	}
	return false
}

// ScanWords is a split function for a Scanner that returns each
// space-separated word of text, with surrounding spaces deleted. It will
// never return an empty string. The definition of space is set by
// unicode.IsSpace.
func ScanWords(data []byte, atEOF bool) (advance int, token []byte, err error) {
	// Skip leading spaces.
	start := 0
	for width := 0; start < len(data); start += width {
		var r rune
		r, width = utf8.DecodeRune(data[start:])
		if !isSpace(r) {
			break
		}
	}
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	// Scan until space, marking end of word.
	for width, i := 0, start; i < len(data); i += width {
		var r rune
		r, width = utf8.DecodeRune(data[i:])
		if isSpace(r) {
			return i + width, data[start:i], nil
		}
	}
	// If we're at EOF, we have a final, non-empty, non-terminated word. Return it.
	if atEOF && len(data) > start {
		return len(data), data[start:], nil
	}
	// Request more data.
	return 0, nil, nil
}

package main

import (
    "fmt"
)

func main() {
    var n, m int
    var baris string
    fmt.Scanln(&n, &m)
    for k:=0; k<n; k+=1 {
        fmt.Scanln(&baris)
        for l:=0; l<m; l+=1 {
            var isi = baris[l]
            if baris[l]=='-' {
                fmt.Printf("-")
            } else {
            if (k+l)%2==0 {
                    isi = 'B'
                } else {
                    isi = 'W'
                }
                fmt.Printf("%c", isi)
        }
    }
        fmt.Println()
    }
}

package main

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

func main() {
	var n, m int
	if _, err := fmt.Scanf("%d %d\n", &n, &m); err != nil {
		return
	}

	board := make([]string, n)

	reader := bufio.NewReader(os.Stdin)
	re := regexp.MustCompile(`\r?\n`)
	for i := 0; i < n; i++ {
		if s, err := reader.ReadString('\n'); err != nil {
			if err == io.EOF {
				break
			} else {
				return
			}
		} else {
			board[i] = re.ReplaceAllString(s, "")
		}
	}

	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if board[i][j] == '-' {
				fmt.Printf("-")
			} else { // board[i][j] == '.'
				if (i+j)%2 == 0 {
					fmt.Printf("B")
				} else {
					fmt.Printf("W")
				}
			}
		}
		fmt.Printf("\n")
	}
}

package main

import "fmt"

func dfs(pi int, pj int, c byte, board [][]byte, di [4]int, dj [4]int) {
    board[pi][pj] = c
    var nc byte
    if c == 'B' { nc = 'W' } else { nc = 'B' }
    for k := 0; k < 4; k++ {
        ni, nj := pi+di[k], pj+dj[k]
        if (ni >= 0) && (ni < len(board)) && (nj >= 0) && (nj < len(board[ni])) && (board[ni][nj] == '.') {
            dfs(ni,nj,nc,board,di,dj)
        }
    }
}

func main() {
    di := [4]int{-1,0,1,0}
    dj := [4]int{0,1,0,-1}
    var n,m int
    var s string
    fmt.Scan(&n,&m)
    board := make([][]byte,n)
    for i := 0; i < n; i++ {
        fmt.Scan(&s)
        board[i] = make([]byte,m)
        for j := 0; j < m; j++ {
            board[i][j] = s[j]
        }
    }

    for i := 0; i < n; i++ {
        for j := 0; j < m; j++ {
            if board[i][j] == '.' {
                dfs(i,j,'B',board,di,dj)
            }
        }
    }

    for i := 0; i < n; i++ {
        for j := 0; j < m; j++ {
            fmt.Print(string(board[i][j]))
        }
        fmt.Println()
    }
}

package main

import (
	"fmt"
)

func main() {
	var n, m int
	fmt.Scan(&n, &m)
	board := make([][]rune, n, n)

	color := func(i, j int) rune {
		if (i+j)%2 == 0 {
			return 'B'
		}
		return 'W'
	}

	for i := 0; i < n; i++ {
		var row string
		fmt.Scan(&row)
		board[i] = make([]rune, m)
		for j := 0; j < m; j++ {
			if row[j] == '.' {
				board[i][j] = color(i, j)
			} else {
				board[i][j] = '-'
			}
		}
	}
	for i := 0; i < n; i++ {
		fmt.Println(string(board[i]))
	}
}

// 445A-mic_rizal
package main

import (
    "fmt"
)

func main() {
    var n, m, x, y int
    var str [11000]string
    fmt.Scan(&n, &m)
    for y = 0; y < n; y++ {
        fmt.Scan(&str[y])
    }
    for x = 0; x < n; x++ {
        for y = 0; y < len(str[x]); y++ {
            if str[x][y] == '.' {
                if (x+y)%2 == 0 {
                    fmt.Print(string('B'))
                } else {
                    fmt.Print(string('W'))
                }
            } else {
                fmt.Print(string('-'))
            }
        }
        fmt.Println()
    }
}

package main

import (
    "fmt"
)

func main() {
    var n, m int
    var row string
    fmt.Scanf("%d%d\n", &n, &m)
    for i:=1; i<=n; i++ {
        fmt.Scanf("%s\n", &row)
        for j:=0; j<m; j++ {
            var cell = row[j]
            if row[j] == '.' {
                if (i+j)%2 == 0 {
                    cell = 'B'
                } else {
                    cell = 'W'
                }
            }
            fmt.Printf("%c", cell)
        }
        fmt.Println()
    }
}

package main

import "fmt"

type board [][]rune

func (b *board) Print() {
	ret := ""
	for _, v1 := range *b {
		for _, v2 := range v1 {
			ret += string(v2)
		}
		ret += "\n"
	}
	fmt.Print(ret)
}

type pos struct {
	i int
	j int
}

func color(b *board, i int, j int) {
	toVisit := map[pos]bool{
		{i, j}: true,
	}
	var curr rune
	curr = 'B'
	for len(toVisit) > 0 {
		toVisitNext := map[pos]bool{}
		for p, _ := range toVisit {
			(*b)[p.i][p.j] = curr
			deltas := []pos{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}
			for _, d := range deltas {
				if p.i+d.i >= 0 && p.i+d.i < len(*b) &&
					p.j+d.j >= 0 && p.j+d.j < len((*b)[p.i+d.i]) &&
					(*b)[p.i+d.i][p.j+d.j] == '.' {
					toVisitNext[pos{p.i + d.i, p.j + d.j}] = true
				}
			}
		}
		toVisit = toVisitNext
		if curr == 'B' {
			curr = 'W'
		} else {
			curr = 'B'
		}
	}
}

func sol(b *board) {
	for i, v := range *b {
		for j, r := range v {
			if r == '.' {
				color(b, i, j)
			}
		}
	}
}

func main() {
	var n, m int64
	fmt.Scanf("%d %d\n", &n, &m)
	b := board{}
	for i := int64(0); i < n; i++ {
		b = append(b, []rune{})
		var s string
		fmt.Scanf("%s\n", &s)
		for _, v := range s {
			b[i] = append(b[i], v)
		}
	}
	sol(&b)
	b.Print()
}

package main

import "fmt"

type board [][]rune

func (b *board) ToString() string {
	ret := ""
	for _, v1 := range *b {
		for _, v2 := range v1 {
			ret += string(v2)
		}
		ret += "\n"
	}
	return ret
}

type pos struct {
	i int
	j int
}

func color(b *board, i int, j int) {
	toVisit := map[pos]bool{
		{i, j}: true,
	}
	var curr rune
	curr = 'B'
	for len(toVisit) > 0 {
		toVisitNext := map[pos]bool{}
		for p, _ := range toVisit {
			(*b)[p.i][p.j] = curr
			deltas := []pos{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}
			for _, d := range deltas {
				if p.i+d.i >= 0 && p.i+d.i < len(*b) &&
					p.j+d.j >= 0 && p.j+d.j < len((*b)[p.i+d.i]) &&
					(*b)[p.i+d.i][p.j+d.j] == '.' {
					toVisitNext[pos{p.i + d.i, p.j + d.j}] = true
				}
			}
		}
		toVisit = toVisitNext
		if curr == 'B' {
			curr = 'W'
		} else {
			curr = 'B'
		}
	}
}

func sol(b *board) {
	for i, v := range *b {
		for j, r := range v {
			if r == '.' {
				color(b, i, j)
			}
		}
	}
}

func main() {
	var n, m int64
	fmt.Scanf("%d %d\n", &n, &m)
	b := board{}
	for i := int64(0); i < n; i++ {
		b = append(b, []rune{})
		var s string
		fmt.Scanf("%s\n", &s)
		for _, v := range s {
			b[i] = append(b[i], v)
		}
	}
	sol(&b)
	fmt.Print(b.ToString())
}

package main

import "fmt"

func p(r [][]rune) {
	for _, r1 := range r {
		for _, r2 := range r1 {
			fmt.Print(string(r2))
		}
		fmt.Print("\n")
	}
}

type pos struct {
	i int
	j int
}

func color(board *[][]rune, i int, j int) {
	toVisit := map[pos]bool{
		{i, j}: true,
	}
	var curr rune
	curr = 'B'
	for len(toVisit) > 0 {
		toVisitNext := map[pos]bool{}
		for p, _ := range toVisit {
			(*board)[p.i][p.j] = curr
			deltas := []pos{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}
			for _, d := range deltas {
				if p.i+d.i >= 0 && p.i+d.i < len(*board) &&
					p.j+d.j >= 0 && p.j+d.j < len((*board)[p.i+d.i]) &&
					(*board)[p.i+d.i][p.j+d.j] == '.' {
					toVisitNext[pos{p.i + d.i, p.j + d.j}] = true
				}
			}
		}
		toVisit = toVisitNext
		if curr == 'B' {
			curr = 'W'
		} else {
			curr = 'B'
		}
	}
}

func sol(board *[][]rune) {
	for i, v := range *board {
		for j, r := range v {
			if r == '.' {
				color(board, i, j)
			}
		}
	}
}

func main() {
	var n, m int64
	fmt.Scanf("%d %d\n", &n, &m)
	board := [][]rune{}
	for i := int64(0); i < n; i++ {
		board = append(board, []rune{})
		var s string
		fmt.Scanf("%s\n", &s)
		for _, v := range s {
			board[i] = append(board[i], v)
		}
	}
	sol(&board)
	p(board)
}

package main

import "fmt"

type board [][]rune

func (b *board) Print() {
	ret := ""
	for _, v1 := range *b {
		for _, v2 := range v1 {
			ret += string(v2)
		}
		ret += "\n"
	}
	fmt.Print(ret)
}

type pos struct {
	i int
	j int
}

func color(b *board, i int, j int) {
	toVisit := map[pos]bool{
		{i, j}: true,
	}
	var curr rune
	curr = 'B'
	for len(toVisit) > 0 {
		toVisitNext := map[pos]bool{}
		for p, _ := range toVisit {
			(*b)[p.i][p.j] = curr
			deltas := []pos{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}
			for _, d := range deltas {
				if p.i+d.i >= 0 && p.i+d.i < len(*b) && p.j+d.j >= 0 && p.j+d.j < len((*b)[p.i+d.i]) && (*b)[p.i+d.i][p.j+d.j] == '.' {
					toVisitNext[pos{p.i + d.i, p.j + d.j}] = true
				}
			}
		}
		toVisit = toVisitNext
		if curr == 'B' {
			curr = 'W'
		} else {
			curr = 'B'
		}
	}
}

func sol(b *board) {
	for i, v := range *b {
		for j, r := range v {
			if r == '.' {
				color(b, i, j)
			}
		}
	}
}

func main() {
	var n, m int64
	fmt.Scan(&n, &m)
	b := board{}
	for i := int64(0); i < n; i++ {
		b = append(b, []rune{})
		var s string
		fmt.Scan(&s)
		for _, v := range s {
			b[i] = append(b[i], v)
		}
	}
	sol(&b)
	b.Print()
}

package main

import "fmt"

func p(r [][]rune) {
	for _, r1 := range r {
		l := ""
		for _, r2 := range r1 {
			l = l + string(r2)
		}
		fmt.Println(l)
	}
}

type pos struct {
	i int
	j int
}

func color(board *[][]rune, i int, j int) {
	toVisit := map[pos]bool{
		{i, j}: true,
	}
	var curr rune
	curr = 'B'
	for len(toVisit) > 0 {
		toVisitNext := map[pos]bool{}
		for p, _ := range toVisit {
			(*board)[p.i][p.j] = curr
			if p.i+1 >= 0 && p.i+1 < len(*board) && (*board)[p.i+1][p.j] == '.' {
				toVisitNext[pos{p.i + 1, p.j}] = true
			}
			if p.i-1 >= 0 && p.i-1 < len(*board) && (*board)[p.i-1][p.j] == '.' {
				toVisitNext[pos{p.i - 1, p.j}] = true
			}
			if p.j+1 >= 0 && p.j+1 < len((*board)[0]) && (*board)[p.i][p.j+1] == '.' {
				toVisitNext[pos{p.i, p.j + 1}] = true
			}
			if p.j-1 >= 0 && p.j-1 < len((*board)[0]) && (*board)[p.i][p.j-1] == '.' {
				toVisitNext[pos{p.i, p.j - 1}] = true
			}
		}
		toVisit = toVisitNext
		if curr == 'B' {
			curr = 'W'
		} else {
			curr = 'B'
		}
	}
}

func sol(board *[][]rune) {
	for i, v := range *board {
		for j, r := range v {
			if r == '.' {
				color(board, i, j)
			}
		}
	}
}

func main() {
	var n, m int64
	fmt.Scanf("%d %d\n", &n, &m)
	board := [][]rune{}
	for i := int64(0); i < n; i++ {
		board = append(board, []rune{})
		var s string
		fmt.Scanf("%s\n", &s)
		for _, v := range s {
			board[i] = append(board[i], v)
		}
	}
	sol(&board)
	p(board)
}

package main

import "fmt"

func p(r [][]rune) {
	for _, r1 := range r {
		for _, r2 := range r1 {
			fmt.Print(string(r2))
		}
		fmt.Print("\n")
	}
}

type pos struct {
	i int
	j int
}

func color(board *[][]rune, i int, j int) {
	toVisit := map[pos]bool{
		{i, j}: true,
	}
	var curr rune
	curr = 'B'
	for len(toVisit) > 0 {
		toVisitNext := map[pos]bool{}
		for p, _ := range toVisit {
			(*board)[p.i][p.j] = curr
			if p.i+1 >= 0 && p.i+1 < len(*board) && (*board)[p.i+1][p.j] == '.' {
				toVisitNext[pos{p.i + 1, p.j}] = true
			}
			if p.i-1 >= 0 && p.i-1 < len(*board) && (*board)[p.i-1][p.j] == '.' {
				toVisitNext[pos{p.i - 1, p.j}] = true
			}
			if p.j+1 >= 0 && p.j+1 < len((*board)[0]) && (*board)[p.i][p.j+1] == '.' {
				toVisitNext[pos{p.i, p.j + 1}] = true
			}
			if p.j-1 >= 0 && p.j-1 < len((*board)[0]) && (*board)[p.i][p.j-1] == '.' {
				toVisitNext[pos{p.i, p.j - 1}] = true
			}
		}
		toVisit = toVisitNext
		if curr == 'B' {
			curr = 'W'
		} else {
			curr = 'B'
		}
	}
}

func sol(board *[][]rune) {
	for i, v := range *board {
		for j, r := range v {
			if r == '.' {
				color(board, i, j)
			}
		}
	}
}

func main() {
	var n, m int64
	fmt.Scanf("%d %d\n", &n, &m)
	board := [][]rune{}
	for i := int64(0); i < n; i++ {
		board = append(board, []rune{})
		var s string
		fmt.Scanf("%s\n", &s)
		for _, v := range s {
			board[i] = append(board[i], v)
		}
	}
	sol(&board)
	p(board)
}

package main

import (
	"bufio"
	"bytes"
	"errors"
	"fmt"
	"io"
	"math/rand"
	"os"
	"strconv"
	"time"
	"unicode/utf8"
)

const ()

var ()

func solve() {
	/*n := readInt()
	firstName := make([]string, n)
	lastName := make([]string, n)
	for i := 0; i < n; i++ {
		firstName[i] = readString()
		lastName[i] = readString()
	}
	p := make([]int, n)
	for i := 0; i < n; i++ {
		p[i] = readInt() - 1
	}
	var last string
	for i := 0; i < n; i++ {
		if last > firstName[p[i]] && last > lastName[p[i]] {
			printString("NO\n")
			return
		}
		if firstName[p[i]] < lastName[p[i]] {
			if last < firstName[p[i]] {
				last = firstName[p[i]]
			} else {
				last = lastName[p[i]]
			}
		} else {
			if last < lastName[p[i]] {
				last = lastName[p[i]]
			} else {
				last = firstName[p[i]]
			}
		}
	}*/

	var n, m int
	var row string
	fmt.Scanf("%d%d\n", &n, &m)
	for i := 1; i <= n; i++ {
		fmt.Scanf("%s\n", &row)
		for j := 0; j < m; j++ {
			var cell = row[j]
			if row[j] == '.' {
				if (i+j)%2 == 0 {
					cell = 'B'
				} else {
					cell = 'W'
				}
			}
			fmt.Printf("%c", cell)
		}
		fmt.Println()
	}

	printString("YES\n")
}

// IO.

var (
	scanner *Scanner
	writer  *bufio.Writer
)

func main() {
	input := os.Stdin
	output := os.Stdout
	//	input, _ := os.Open("")
	//	output, _ := os.Create("")

	defer input.Close()
	defer output.Close()

	scanner = NewScanner(input)
	scanner.Split(bufio.ScanWords)

	writer = bufio.NewWriter(output)
	defer writer.Flush()

	rand.Seed(int64(time.Now().Nanosecond()))
	solve()
}

// Read.

func readString() string {
	scanner.Scan()
	ans := scanner.Text()
	return ans
}

func readLine() string {
	scanner.Split(bufio.ScanLines)
	defer scanner.Split(bufio.ScanWords)
	return readString()
}

func readInt() int {
	ans, _ := strconv.ParseInt(readString(), 10, 0)
	return int(ans)
}

func readInt64() int64 {
	ans, _ := strconv.ParseInt(readString(), 10, 64)
	return ans
}

func readFloat64() float64 {
	ans, _ := strconv.ParseFloat(readString(), 64)
	return ans
}

// Write.

func printString(value string) {
	writer.WriteString(value)
}

func printLine() {
	printString("\n")
}

func printSpace() {
	printString(" ")
}

func printInt(value int) {
	printString(strconv.FormatInt(int64(value), 10))
}

func printInt64(value int64) {
	printString(strconv.FormatInt(value, 10))
}

func printFloat64(value float64) {
	printString(strconv.FormatFloat(value, 'f', 20, 64))
}

// Tuple

type Tuple struct {
	a, b int
}

func (p Tuple) Equals(key Key) bool {
	return p.a == key.(Tuple).a
}

func (p Tuple) Less(key Key) bool {
	return p.a < key.(Tuple).a
}

type TupleSlice []Tuple

func (p TupleSlice) Len() int {
	return len(p)
}

func (p TupleSlice) Less(j, i int) bool {
	return p[j].a < p[i].a
}

func (p TupleSlice) Swap(j, i int) {
	p[j], p[i] = p[i], p[j]
}

// Min, max, abs.

func maxInt(a, b int) int {
	if a > b {
		return a
	} else {
		return b
	}
}

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

func absInt(a int) int {
	if a > 0 {
		return a
	} else {
		return -a
	}
}

func maxInt64(a, b int64) int64 {
	if a > b {
		return a
	} else {
		return b
	}
}

func minInt64(a, b int64) int64 {
	if a < b {
		return a
	} else {
		return b
	}
}

func absInt64(a int64) int64 {
	if a > 0 {
		return a
	} else {
		return -a
	}
}

func maxFloat64(a, b float64) float64 {
	if a > b {
		return a
	} else {
		return b
	}
}

func minFloat64(a, b float64) float64 {
	if a < b {
		return a
	} else {
		return b
	}
}

func absFloat64(a float64) float64 {
	if a > 0 {
		return a
	} else {
		return -a
	}
}

// Set Key interface implementations.

type Int int

func (p Int) Equals(key Key) bool {
	return int(p) == int(key.(Int))
}

func (p Int) Less(key Key) bool {
	return int(p) < int(key.(Int))
}

// Set.

type Key interface {
	Equals(key Key) bool
	Less(key Key) bool
}

type node struct {
	key   Key
	left  *node
	right *node
}

func newNode(key Key) *node {
	return &node{key, nil, nil}
}

type SplayTree struct {
	root *node
	tmp  *node
	len  int
}

func NewSplayTree() *SplayTree {
	return &SplayTree{nil, newNode(nil), 0}
}

func rotateLeft(x, p *node) {
	p.right = x.left
	x.left = p
}

func rotateRight(x, p *node) {
	p.left = x.right
	x.right = p
}

func (p *SplayTree) splay(x *node, key Key) *node {
	if x == nil {
		return nil
	}

	left := p.tmp
	right := p.tmp

	for {
		if key.Less(x.key) {
			y := x.left
			if y == nil {
				break
			}
			if key.Less(y.key) { // zig-zig
				rotateRight(y, x)
				x = y
				if x.left == nil {
					break
				}
			}
			// link right
			right.left = x
			right = x
			// move left
			x = x.left
		} else if x.key.Less(key) {
			y := x.right
			if y == nil {
				break
			}
			if y.key.Less(key) { // zig-zig
				rotateLeft(y, x)
				x = y
				if x.right == nil {
					break
				}
			}
			// link left
			left.right = x
			left = x
			// move right
			x = x.right
		} else {
			break
		}
	}

	left.right = x.left
	right.left = x.right
	x.left = p.tmp.right
	x.right = p.tmp.left

	return x
}

// left <= key < right
func (p *SplayTree) split(key Key) (left, right *node) {
	p.root = p.splay(p.root, key)
	if p.root.key.Equals(key) || p.root.key.Less(key) {
		right := p.root.right
		p.root.right = nil
		return p.root, right
	} else {
		left := p.root.left
		p.root.left = nil
		return left, p.root
	}
}

// keys from left tree must be less then keys from right tree
func (p *SplayTree) join(left, right *node) *node {
	if left == nil {
		return right
	} else if right == nil {
		return left
	}
	left = p.splay(left, right.key)
	left.right = right
	return left
}

type Set interface {
	Len() int
	Insert(key Key) error
	Find(key Key) bool
	Remove(key Key) error
}

func NewSet() Set {
	return Set(NewSplayTree())
}

func (p *SplayTree) Len() int {
	return p.len
}

func (p *SplayTree) Insert(key Key) error {
	if p.root == nil {
		p.root = newNode(key)
		p.len++
	} else {
		p.root = p.splay(p.root, key)
		if p.root.key.Equals(key) {
			return errors.New("Such key already exists")
		} else {
			left, right := p.split(key)
			p.root = newNode(key)
			p.root.left = left
			p.root.right = right
			p.len++
		}
	}
	return nil
}

func (p *SplayTree) Find(key Key) bool {
	if p.root == nil {
		return false
	}
	p.root = p.splay(p.root, key)
	return p.root.key.Equals(key)
}

func (p *SplayTree) Remove(key Key) error {
	p.root = p.splay(p.root, key)
	if p.root == nil || !p.root.key.Equals(key) {
		return errors.New("Such key doesn't exist")
	}
	p.root = p.join(p.split(key))
	return nil
}

// Copied scan.go
// Scanner provides a convenient interface for reading data such as
// a file of newline-delimited lines of text. Successive calls to
// the Scan method will step through the 'tokens' of a file, skipping
// the bytes between the tokens. The specification of a token is
// defined by a split function of type SplitFunc; the default split
// function breaks the input into lines with line termination stripped. Split
// functions are defined in this package for scanning a file into
// lines, bytes, UTF-8-encoded runes, and space-delimited words. The
// client may instead provide a custom split function.
//
// Scanning stops unrecoverably at EOF, the first I/O error, or a token too
// large to fit in the buffer. When a scan stops, the reader may have
// advanced arbitrarily far past the last token. Programs that need more
// control over error handling or large tokens, or must run sequential scans
// on a reader, should use bufio.Reader instead.
//
type Scanner struct {
	r            io.Reader // The reader provided by the client.
	split        SplitFunc // The function to split the tokens.
	maxTokenSize int       // Maximum size of a token; modified by tests.
	token        []byte    // Last token returned by split.
	buf          []byte    // Buffer used as argument to split.
	start        int       // First non-processed byte in buf.
	end          int       // End of data in buf.
	err          error     // Sticky error.
}

// SplitFunc is the signature of the split function used to tokenize the
// input. The arguments are an initial substring of the remaining unprocessed
// data and a flag, atEOF, that reports whether the Reader has no more data
// to give. The return values are the number of bytes to advance the input
// and the next token to return to the user, plus an error, if any. If the
// data does not yet hold a complete token, for instance if it has no newline
// while scanning lines, SplitFunc can return (0, nil, nil) to signal the
// Scanner to read more data into the slice and try again with a longer slice
// starting at the same point in the input.
//
// If the returned error is non-nil, scanning stops and the error
// is returned to the client.
//
// The function is never called with an empty data slice unless atEOF
// is true. If atEOF is true, however, data may be non-empty and,
// as always, holds unprocessed text.
type SplitFunc func(data []byte, atEOF bool) (advance int, token []byte, err error)

// Errors returned by Scanner.
var (
	ErrTooLong         = errors.New("bufio.Scanner: token too long")
	ErrNegativeAdvance = errors.New("bufio.Scanner: SplitFunc returns negative advance count")
	ErrAdvanceTooFar   = errors.New("bufio.Scanner: SplitFunc returns advance count beyond input")
)

const (
	// Maximum size used to buffer a token. The actual maximum token size
	// may be smaller as the buffer may need to include, for instance, a newline.
	MaxScanTokenSize = 1 << 20
)

// NewScanner returns a new Scanner to read from r.
// The split function defaults to ScanLines.
func NewScanner(r io.Reader) *Scanner {
	return &Scanner{
		r:            r,
		split:        ScanLines,
		maxTokenSize: MaxScanTokenSize,
		buf:          make([]byte, 4096), // Plausible starting size; needn't be large.
	}
}

// Err returns the first non-EOF error that was encountered by the Scanner.
func (s *Scanner) Err() error {
	if s.err == io.EOF {
		return nil
	}
	return s.err
}

// Bytes returns the most recent token generated by a call to Scan.
// The underlying array may point to data that will be overwritten
// by a subsequent call to Scan. It does no allocation.
func (s *Scanner) Bytes() []byte {
	return s.token
}

// Text returns the most recent token generated by a call to Scan
// as a newly allocated string holding its bytes.
func (s *Scanner) Text() string {
	return string(s.token)
}

// Scan advances the Scanner to the next token, which will then be
// available through the Bytes or Text method. It returns false when the
// scan stops, either by reaching the end of the input or an error.
// After Scan returns false, the Err method will return any error that
// occurred during scanning, except that if it was io.EOF, Err
// will return nil.
func (s *Scanner) Scan() bool {
	// Loop until we have a token.
	for {
		// See if we can get a token with what we already have.
		if s.end > s.start {
			advance, token, err := s.split(s.buf[s.start:s.end], s.err != nil)
			if err != nil {
				s.setErr(err)
				return false
			}
			if !s.advance(advance) {
				return false
			}
			s.token = token
			if token != nil {
				return true
			}
		}
		// We cannot generate a token with what we are holding.
		// If we've already hit EOF or an I/O error, we are done.
		if s.err != nil {
			// Shut it down.
			s.start = 0
			s.end = 0
			return false
		}
		// Must read more data.
		// First, shift data to beginning of buffer if there's lots of empty space
		// or space is neded.
		if s.start > 0 && (s.end == len(s.buf) || s.start > len(s.buf)/2) {
			copy(s.buf, s.buf[s.start:s.end])
			s.end -= s.start
			s.start = 0
		}
		// Is the buffer full? If so, resize.
		if s.end == len(s.buf) {
			if len(s.buf) >= s.maxTokenSize {
				s.setErr(ErrTooLong)
				return false
			}
			newSize := len(s.buf) * 2
			if newSize > s.maxTokenSize {
				newSize = s.maxTokenSize
			}
			newBuf := make([]byte, newSize)
			copy(newBuf, s.buf[s.start:s.end])
			s.buf = newBuf
			s.end -= s.start
			s.start = 0
			continue
		}
		// Finally we can read some input. Make sure we don't get stuck with
		// a misbehaving Reader. Officially we don't need to do this, but let's
		// be extra careful: Scanner is for safe, simple jobs.
		for loop := 0; ; {
			n, err := s.r.Read(s.buf[s.end:len(s.buf)])
			s.end += n
			if err != nil {
				s.setErr(err)
				break
			}
			if n > 0 {
				break
			}
			loop++
			if loop > 100 {
				s.setErr(io.ErrNoProgress)
				break
			}
		}
	}
}

// advance consumes n bytes of the buffer. It reports whether the advance was legal.
func (s *Scanner) advance(n int) bool {
	if n < 0 {
		s.setErr(ErrNegativeAdvance)
		return false
	}
	if n > s.end-s.start {
		s.setErr(ErrAdvanceTooFar)
		return false
	}
	s.start += n
	return true
}

// setErr records the first error encountered.
func (s *Scanner) setErr(err error) {
	if s.err == nil || s.err == io.EOF {
		s.err = err
	}
}

// Split sets the split function for the Scanner. If called, it must be
// called before Scan. The default split function is ScanLines.
func (s *Scanner) Split(split SplitFunc) {
	s.split = split
}

// Split functions

// ScanBytes is a split function for a Scanner that returns each byte as a token.
func ScanBytes(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	return 1, data[0:1], nil
}

var errorRune = []byte(string(utf8.RuneError))

// ScanRunes is a split function for a Scanner that returns each
// UTF-8-encoded rune as a token. The sequence of runes returned is
// equivalent to that from a range loop over the input as a string, which
// means that erroneous UTF-8 encodings translate to U+FFFD = "\xef\xbf\xbd".
// Because of the Scan interface, this makes it impossible for the client to
// distinguish correctly encoded replacement runes from encoding errors.
func ScanRunes(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}

	// Fast path 1: ASCII.
	if data[0] < utf8.RuneSelf {
		return 1, data[0:1], nil
	}

	// Fast path 2: Correct UTF-8 decode without error.
	_, width := utf8.DecodeRune(data)
	if width > 1 {
		// It's a valid encoding. Width cannot be one for a correctly encoded
		// non-ASCII rune.
		return width, data[0:width], nil
	}

	// We know it's an error: we have width==1 and implicitly r==utf8.RuneError.
	// Is the error because there wasn't a full rune to be decoded?
	// FullRune distinguishes correctly between erroneous and incomplete encodings.
	if !atEOF && !utf8.FullRune(data) {
		// Incomplete; get more bytes.
		return 0, nil, nil
	}

	// We have a real UTF-8 encoding error. Return a properly encoded error rune
	// but advance only one byte. This matches the behavior of a range loop over
	// an incorrectly encoded string.
	return 1, errorRune, nil
}

// dropCR drops a terminal \r from the data.
func dropCR(data []byte) []byte {
	if len(data) > 0 && data[len(data)-1] == '\r' {
		return data[0 : len(data)-1]
	}
	return data
}

// ScanLines is a split function for a Scanner that returns each line of
// text, stripped of any trailing end-of-line marker. The returned line may
// be empty. The end-of-line marker is one optional carriage return followed
// by one mandatory newline. In regular expression notation, it is `\r?\n`.
// The last non-empty line of input will be returned even if it has no
// newline.
func ScanLines(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	if i := bytes.IndexByte(data, '\n'); i >= 0 {
		// We have a full newline-terminated line.
		return i + 1, dropCR(data[0:i]), nil
	}
	// If we're at EOF, we have a final, non-terminated line. Return it.
	if atEOF {
		return len(data), dropCR(data), nil
	}
	// Request more data.
	return 0, nil, nil
}

// isSpace reports whether the character is a Unicode white space character.
// We avoid dependency on the unicode package, but check validity of the implementation
// in the tests.
func isSpace(r rune) bool {
	if r <= '\u00FF' {
		// Obvious ASCII ones: \t through \r plus space. Plus two Latin-1 oddballs.
		switch r {
		case ' ', '\t', '\n', '\v', '\f', '\r':
			return true
		case '\u0085', '\u00A0':
			return true
		}
		return false
	}
	// High-valued ones.
	if '\u2000' <= r && r <= '\u200a' {
		return true
	}
	switch r {
	case '\u1680', '\u180e', '\u2028', '\u2029', '\u202f', '\u205f', '\u3000':
		return true
	}
	return false
}

// ScanWords is a split function for a Scanner that returns each
// space-separated word of text, with surrounding spaces deleted. It will
// never return an empty string. The definition of space is set by
// unicode.IsSpace.
func ScanWords(data []byte, atEOF bool) (advance int, token []byte, err error) {
	// Skip leading spaces.
	start := 0
	for width := 0; start < len(data); start += width {
		var r rune
		r, width = utf8.DecodeRune(data[start:])
		if !isSpace(r) {
			break
		}
	}
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	// Scan until space, marking end of word.
	for width, i := 0, start; i < len(data); i += width {
		var r rune
		r, width = utf8.DecodeRune(data[i:])
		if isSpace(r) {
			return i + width, data[start:i], nil
		}
	}
	// If we're at EOF, we have a final, non-empty, non-terminated word. Return it.
	if atEOF && len(data) > start {
		return len(data), data[start:], nil
	}
	// Request more data.
	return 0, nil, nil
}

// 445A-mic_rizal
package main

import (
    "fmt"
)

func main() {
    var n, m, x, y int
    var str [110]string
    fmt.Scan(&n, &m)
    for y = 1; y <= m; y++ {
        fmt.Scan(&str[y])
    }
    for x = 1; x <= n; x++ {
        for y = 0; y < m; y++ {
            if str[x][y] == '.' {
                if (x+y)%2 == 0 {
                    fmt.Print(string('B'))
                    fmt.Print(" ")
                } else {
                    fmt.Print(string('W'))
                    fmt.Print(" ")
                }
            } else {
                fmt.Print(string('-'))
                fmt.Print(" ")
            }
        }
        fmt.Println()
    }
}

package main

import "fmt"

func p(r [][]rune) {
	for _, r1 := range r {
		for _, r2 := range r1 {
			fmt.Print(string(r2))
		}
		fmt.Print("\n")
	}
}

type pos struct {
	i int
	j int
}

func color(board *[][]rune, i int, j int) {
	toVisit := map[pos]bool{
		{i, j}: true,
	}
	var curr rune
	curr = 'B'
	for len(toVisit) > 0 {
		toVisitNext := map[pos]bool{}
		for p, _ := range toVisit {
			(*board)[p.i][p.j] = curr
			if p.i+1 >= 0 && p.i+1 < len(*board) && (*board)[p.i+1][p.j] == '.' {
				toVisitNext[pos{p.i + 1, p.j}] = true
			}
			if p.i-1 >= 0 && p.i-1 < len(*board) && (*board)[p.i-1][p.j] == '.' {
				toVisitNext[pos{p.i - 1, p.j}] = true
			}
			if p.j+1 >= 0 && p.j+1 < len((*board)[0]) && (*board)[p.i][p.j+1] == '.' {
				toVisitNext[pos{p.i, p.j + 1}] = true
			}
			if p.j-1 >= 0 && p.j-1 < len((*board)[0]) && (*board)[p.i][p.j-1] == '.' {
				toVisitNext[pos{p.i, p.j - 1}] = true
			}
		}
		toVisit = toVisitNext
		if curr == 'B' {
			curr = 'W'
		} else {
			curr = 'B'
		}
	}
}

func sol(board *[][]rune) {
	for i, v := range *board {
		for j, r := range v {
			if r == '.' {
				color(board, i, j)
			}
		}
	}
}

func main() {
	var n, m int64
	fmt.Scanf("%d %d", &n, &m)
	board := [][]rune{}
	for i := int64(0); i < n; i++ {
		board = append(board, []rune{})
		var s string
		fmt.Scanf("%s\n", &s)
		for _, v := range s {
			board[i] = append(board[i], v)
		}
	}
	sol(&board)
	p(board)
}

package main

import "fmt"

func p(r [][]rune) {
	for _, r1 := range r {
		l := ""
		for _, r2 := range r1 {
			l = l + string(r2)
		}
		fmt.Println(l)
	}
}

type pos struct {
	i int
	j int
}

func color(board *[][]rune, i int, j int) {
	toVisit := map[pos]bool{
		{i, j}: true,
	}
	var curr rune
	curr = 'B'
	for len(toVisit) > 0 {
		toVisitNext := map[pos]bool{}
		for p, _ := range toVisit {
			(*board)[p.i][p.j] = curr
			if p.i+1 >= 0 && p.i+1 < len(*board) && (*board)[p.i+1][p.j] == '.' {
				toVisitNext[pos{p.i + 1, p.j}] = true
			}
			if p.i-1 >= 0 && p.i-1 < len(*board) && (*board)[p.i-1][p.j] == '.' {
				toVisitNext[pos{p.i - 1, p.j}] = true
			}
			if p.j+1 >= 0 && p.j+1 < len((*board)[0]) && (*board)[p.i][p.j+1] == '.' {
				toVisitNext[pos{p.i, p.j + 1}] = true
			}
			if p.j-1 >= 0 && p.j-1 < len((*board)[0]) && (*board)[p.i][p.j-1] == '.' {
				toVisitNext[pos{p.i, p.j - 1}] = true
			}
		}
		toVisit = toVisitNext
		if curr == 'B' {
			curr = 'W'
		} else {
			curr = 'B'
		}
	}
}

func sol(board *[][]rune) {
	for i, v := range *board {
		for j, r := range v {
			if r == '.' {
				color(board, i, j)
			}
		}
	}
}

func main() {
	var n, m int64
	fmt.Scanf("%d %d", &n, &m)
	board := [][]rune{}
	for i := int64(0); i < n; i++ {
		board = append(board, []rune{})
		var s string
		fmt.Scanf("%s\n", &s)
		for _, v := range s {
			board[i] = append(board[i], v)
		}
	}
	fmt.Println("A", board)
	sol(&board)
	fmt.Println("B", board)
	p(board)
	fmt.Println("C", board)
}

package main

import "fmt"

func p(r [][]rune) {
	for _, r1 := range r {
		l := ""
		for _, r2 := range r1 {
			l = l + string(r2)
		}
		fmt.Println(l)
	}
}

type pos struct {
	i int
	j int
}

func color(board *[][]rune, i int, j int) {
	toVisit := map[pos]bool{
		{i, j}: true,
	}
	var curr rune
	curr = 'B'
	for len(toVisit) > 0 {
		toVisitNext := map[pos]bool{}
		for p, _ := range toVisit {
			(*board)[p.i][p.j] = curr
			if p.i+1 >= 0 && p.i+1 < len(*board) && (*board)[p.i+1][p.j] == '.' {
				toVisitNext[pos{p.i + 1, p.j}] = true
			}
			if p.i-1 >= 0 && p.i-1 < len(*board) && (*board)[p.i-1][p.j] == '.' {
				toVisitNext[pos{p.i - 1, p.j}] = true
			}
			if p.j+1 >= 0 && p.j+1 < len((*board)[0]) && (*board)[p.i][p.j+1] == '.' {
				toVisitNext[pos{p.i, p.j + 1}] = true
			}
			if p.j-1 >= 0 && p.j-1 < len((*board)[0]) && (*board)[p.i][p.j-1] == '.' {
				toVisitNext[pos{p.i, p.j - 1}] = true
			}
		}
		toVisit = toVisitNext
		if curr == 'B' {
			curr = 'W'
		} else {
			curr = 'B'
		}
	}
}

func sol(board *[][]rune) {
	for i, v := range *board {
		for j, r := range v {
			if r == '.' {
				color(board, i, j)
			}
		}
	}
}

func main() {
	var n, m int64
	fmt.Scanf("%d %d", &n, &m)
	board := [][]rune{}
	for i := int64(0); i < n; i++ {
		board = append(board, []rune{})
		var s string
		fmt.Scanf("%s\n", &s)
		for _, v := range s {
			board[i] = append(board[i], v)
		}
	}
	sol(&board)
	p(board)
}

package main

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

func p(r [][]rune) {
	f := bufio.NewWriter(os.Stdout)
	defer f.Flush()
	for _, r1 := range r {
		for _, r2 := range r1 {
			f.Write([]byte(string(r2)))
		}
		f.Write([]byte("\n"))
	}
}

type pos struct {
	i int
	j int
}

func color(board *[][]rune, i int, j int) {
	toVisit := map[pos]bool{
		{i, j}: true,
	}
	var curr rune
	curr = 'B'
	for len(toVisit) > 0 {
		toVisitNext := map[pos]bool{}
		for p, _ := range toVisit {
			(*board)[p.i][p.j] = curr
			if p.i+1 >= 0 && p.i+1 < len(*board) && (*board)[p.i+1][p.j] == '.' {
				toVisitNext[pos{p.i + 1, p.j}] = true
			}
			if p.i-1 >= 0 && p.i-1 < len(*board) && (*board)[p.i-1][p.j] == '.' {
				toVisitNext[pos{p.i - 1, p.j}] = true
			}
			if p.j+1 >= 0 && p.j+1 < len((*board)[0]) && (*board)[p.i][p.j+1] == '.' {
				toVisitNext[pos{p.i, p.j + 1}] = true
			}
			if p.j-1 >= 0 && p.j-1 < len((*board)[0]) && (*board)[p.i][p.j-1] == '.' {
				toVisitNext[pos{p.i, p.j - 1}] = true
			}
		}
		toVisit = toVisitNext
		if curr == 'B' {
			curr = 'W'
		} else {
			curr = 'B'
		}
	}
}

func sol(board *[][]rune) {
	for i, v := range *board {
		for j, r := range v {
			if r == '.' {
				color(board, i, j)
			}
		}
	}
}

func main() {
	var n, m int64
	fmt.Scanf("%d %d", &n, &m)
	board := [][]rune{}
	for i := int64(0); i < n; i++ {
		board = append(board, []rune{})
		var s string
		fmt.Scanf("%s\n", &s)
		for _, v := range s {
			board[i] = append(board[i], v)
		}
	}
	sol(&board)
	p(board)
}