Madoka's father just reached $$$1$$$ million subscribers on Mathub! So the website decided to send him a personalized award — The Mathhub's Bit Button! The Bit Button is a rectangular table with $$$n$$$ rows and $$$m$$$ columns with $$$0$$$ or $$$1$$$ in each cell. After exploring the table Madoka found out that: A subrectangle $$$A$$$ is contained in a subrectangle $$$B$$$ if there's no cell contained in $$$A$$$ but not contained in $$$B$$$. Two subrectangles intersect if there is a cell contained in both of them. A subrectangle is called black if there's no cell with value $$$0$$$ inside it. A subrectangle is called nice if it's black and it's not contained in another black subrectangle. The table is called elegant if there are no two nice intersecting subrectangles.For example, in the first illustration the red subrectangle is nice, but in the second one it's not, because it's contained in the purple subrectangle.  Help Madoka to determine whether the table is elegant.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains two positive integers $$$n, m$$$ ($$$1 \le n, m \le 100$$$). The next $$$n$$$ lines contain strings of length $$$m$$$ consisting of zeros and ones — the description of the table. It is guaranteed that the sum of the values of $$$n$$$ and the sum of the values of $$$m$$$ for all test cases do not exceed $$$777$$$.

For each test case print "YES" if its table is elegant or print "NO" otherwise. You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as positive answer).

NoteIn the second test case the table is not elegant, because the red and the purple subrectangles are nice and intersect.   In the fourth test case the table is not elegant, because the red and the purple subrectangles are nice and intersect.

// const { readline, print } = require('@ip-algorithmics/codeforces-io');

function hasOnlyOneEmptyInSquare(array, a, b) {
  var countZero = 0;

  for (var i = 0; i < 2; ++i) {
    for (var j = 0; j < 2; ++j) {
      if (array[a+i][b+j] === 0) {
        countZero++;
      }
    }
  }

  return countZero === 1;
}

var line = readline().split(' ').map(x => parseInt(x))
var testCases = line[0]

var n, m
while (testCases--) {
  line = readline().split(' ').map(x => parseInt(x))
  n = line[0]
  m = line[1]

  var array = new Array(n)

  for (var i = 0; i < n ; ++i) {
    array[i] = [];
    line = readline();

    for (var j = 0; j < line.length; ++j) {
      array[i].push(parseInt(line[j]));
    }
  }

  if (n < 2 || m < 2) {
    print('YES')
    continue;
  }

  var isElegant = true;
  for (i = 0; i < array.length - 1; i++) {
    for (j = 0; j < array[i].length - 1; j++) {
      if (hasOnlyOneEmptyInSquare(array, i, j)) {
        isElegant = false;
      }
    }
  }

  print (isElegant ? 'YES' : 'NO')
}

var tests = parseInt(readline());
    var n,m;
    var mat;
    var visited;

    function checkSquare(i, j) {
        visited[i][j] = 1;
        var col = j;
        while (col < m && mat[i][col]) {
            col++;
            visited[i][col] = 1;
        }
        var width = col - j;

        var row = i+1;
        while (row < n && mat[row][j]) {
            if (j > 0 && mat[row][j-1]) {
                return false;
            }
            col = j;
            while (col < j + width) {
                visited[row][col] = 1;
                if (!mat[row][col]) {
                    return false;
                }
                col++;
            }
            visited[row][col] = 1;
            if (mat[row][col]) {
                return false;
            }
            row++;
        }
        if (row < n) {
            for (var c = j; c < j + width; c++) {
                visited[row][c] = 1;
                if (mat[row][c]) {
                    return false;
                }
            }
        }

        return true;
    }

    for (var t=0; t < tests; t++) {
        var nm = readline().split(' ').map(x=>parseInt(x));
        n = nm[0];
        m = nm[1];
        mat = [];
        visited = [];
        for (var i = 0; i < n; i++) {
            mat.push(readline().split('').map(x=>parseInt(x)));
            visited.push(new Array(m).fill(0));
        }

        var ans = 'YES';
        for (var i = 0; i < n; i++) {
            for (var j = 0; j < m; j++) {
                if (visited[i][j]) {
                    continue;
                }
                if (!mat[i][j]) {
                    visited[i][j] = 1;
                    continue;
                }
                if (checkSquare(i, j)) {
                    continue;
                }
                ans = 'NO';
            }
        }
        print(ans);
    }

"use strict";

process.stdin.resume();
process.stdin.setEncoding("utf-8");

let inputStr = "";
let currentLne = 0;

process.stdin.on('data' , inputStdin =>{

	 inputStr += inputStdin;
})

process.stdin.on('end' , _ =>{
    inputStr = inputStr.trim().split('\n').map( string =>{
    	return string.trim();
    })

main();
})

function readline(){
   return inputStr[currentLne++];
}

function main(){

    let t = parseInt(readline());
    let c= 0;
    while(c<t){

      let m = readline().split(" ").map(a =>parseInt(a));
      let m0 = m[0];
      let countRow = 0 ;
      let arr =[];
      while(countRow < m0){
        let row = readline().split("").map(b=>parseInt(b));
        arr.push(row);
        countRow++;
      }

    let eleg =true;
    let count =0;
    // for (var k = 0; k < arr.length; k++) {
    //     if(arr[k].indexOf(1) == -1 ){
    //          count++;
    //     }
    // }

    for (var i = 0; i < arr.length-1; i++) {

        for (var j = 0; j < arr[0].length; j++) {

           //

          if(arr[i][j] ==1){
               if(j !==0 && arr[i+1][j] ==1 && arr[i+1][j-1] ==1 && arr[i][j-1] ==0 ){
                    eleg= false;
                    // console.log(i,j,"1st")
                    break;
               }

               if(arr[i+1][j]==1 && arr[i+1][j+1] ==1 && arr[i][j+1] == 0){
                   eleg =false;
                    // console.log(i,j,"2st")
                    break;
               }

               if(arr[i][j+1]==1 && arr[i+1][j]==1 && arr[i+1][j+1] ==0){
                eleg = false;
                 // console.log(i,j,"3st")
                 break;
               }

               if(i !== 0 && arr[i][j+1]==1 && arr[i-1][j+1] == 1 && arr[i-1][j] == 0){
                eleg =false;
                 // console.log(i,j,"4st")
                 break;
               }

               if(arr[i][j+1]==1 && arr[i+1][j+1] ==1 && arr[i+1][j]==0){
                eleg =false;
                // console.log(i,j,"5st")
                break;
               }
          }
        }

    }

    // if(count == arr.length*arr[0].length ){
    //     eleg = false;
    // }

    if(eleg){
        console.log("yes");
    }else{
        console.log("no");
    }

    c++;
    }

}

//type input.txt | node code.js

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let [n, m] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr = [];
    for (let i = 0; i < n; i++)
      arr.push(
        readline()
          .trim()
          .split("")
          .map((cur) => parseInt(cur))
      );
    let sum = true;
    for (let i = 0; i < n - 1; i++) {
      for (let j = 0; j < m - 1; j++) {
        if (
          arr[i][j] + arr[i + 1][j] + arr[i][j + 1] + arr[i + 1][j + 1] ===
          3
        ) {
          sum = false;
          break;
        }
      }
    }
    console.log(`${sum === true ? "YES" : "NO"}`);
  }
};
solve();

'use strict';

var readline = require('readline');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, m, s) {
  const sum = Array.from({
    length: n
  }, () => new Array(m).fill(0));
  for (let i = 0; i < n; i++) {
    for (let j = 0; j < m; j++) {
      var _sum$j, _sum, _sum$i, _sum2, _sum3;
      sum[i][j] = ((_sum$j = (_sum = sum[i - 1]) === null || _sum === void 0 ? void 0 : _sum[j]) !== null && _sum$j !== void 0 ? _sum$j : 0) + ((_sum$i = sum[i][j - 1]) !== null && _sum$i !== void 0 ? _sum$i : 0) - ((_sum2 = (_sum3 = sum[i - 1]) === null || _sum3 === void 0 ? void 0 : _sum3[j - 1]) !== null && _sum2 !== void 0 ? _sum2 : 0) + Number(s[i][j]);
    }
  }
  const p = [...new Array(n * m).keys()];
  const find = i => {
    if (p[i] !== i) p[i] = find(p[p[i]]);
    return p[i];
  };
  const union = (i, j) => {
    const ri = find(i),
          rj = find(j);
    if (ri !== rj) p[rj] = ri;
  };
  const dirs = [[0, 1], [1, 0]];
  for (let i = 0; i < n; i++) {
    for (let j = 0; j < m; j++) {
      const a = i * m + j;
      if (s[i][j] === '0') {
        p[a] = -1;
        continue;
      }
      for (let [di, dj] of dirs) {
        const ni = di + i,
              nj = dj + j,
              b = ni * m + nj;
        if (ni < 0 || ni >= n || nj < 0 || nj >= m || s[ni][nj] === '0') continue;
        union(a, b);
      }
    }
  }
  const scc = new Map();
  for (let [i, num] of p.entries()) {
    if (num === -1) continue;
    const root = find(num);
    if (!scc.has(root)) scc.set(root, []);
    scc.get(root).push(i);
  }
  for (let [, points] of scc) {
    var _sum$rb, _sum$rr, _sum4, _sum5, _sum6;
    let ll = Infinity,
        lt = Infinity,
        rr = -Infinity,
        rb = -Infinity;
    for (let num of points) {
      const i = Math.floor(num / m),
            j = num % m;
      ll = Math.min(ll, j);
      lt = Math.min(lt, i);
      rr = Math.max(rr, j);
      rb = Math.max(rb, i);
    }
    if (sum[rb][rr] - ((_sum$rb = sum[rb][ll - 1]) !== null && _sum$rb !== void 0 ? _sum$rb : 0) - ((_sum$rr = (_sum4 = sum[lt - 1]) === null || _sum4 === void 0 ? void 0 : _sum4[rr]) !== null && _sum$rr !== void 0 ? _sum$rr : 0) + ((_sum5 = (_sum6 = sum[lt - 1]) === null || _sum6 === void 0 ? void 0 : _sum6[ll - 1]) !== null && _sum5 !== void 0 ? _sum5 : 0) !== (rr - ll + 1) * (rb - lt + 1)) return 'NO';
  }
  return 'YES';
}

async function main(read) {
  let t = Number(await read());
  let res = [];
  while (t--) {
    const [n, m] = (await read()).split(' ').map(Number);
    const a = [];
    let tmp = n;
    while (tmp--) {
      a.push(await read());
    }
    res.push(solve(n, m, a));
  }
  console.log(res.join('\n'));
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict';

let cin = '';
let current_line = 0;

function     next() { return cin[current_line++]; }
function  nextInt() { return parseInt(next()); }
function nextList() { return next().split(' ').map(s => parseInt(s)); }
function   print(x) { process.stdout.write(x); }

function ones_in_2x2(s, i, j) {
    let count = 0;
    for (let u = i, k = 0; k < 2; ++k, ++u)
        for (let v = j, l = 0; l < 2; ++l, ++v)
            if (s[u][v] == '1')
                ++count;
    return count; }

function main() {
    for (let t = nextInt(); t > 0; --t) {
        const size = nextList();
        const n = size[0], p = n-1, q = size[1]-1;
        let s = Array(n);
        for (let i = 0; i < n; ++i)
            s[i] = next();
        let elegant = true;
        for (let i = 0; i < p && elegant; ++i)
            for (let j = 0; j < q && elegant; ++j)
                elegant = ones_in_2x2(s,i,j) != 3;
        console.log(elegant? "YES": "NO"); } }

process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', line => { cin += line; });
process.stdin.on('end', _ => {
    cin = cin.trim().split('\n').map(line => { return line.trim(); });
    main(); });

'use strict';

let cin = '';
let current_line = 0;

function     next() { return cin[current_line++]; }
function  nextInt() { return parseInt(next()); }
function nextList() { return next().split(' ').map(s => parseInt(s)); }
function   print(x) { process.stdout.write(x); }

function ones_in_2x2(s, i, j) {
    let count = 0;
    for (let u = i, k = 0; k < 2; ++k, ++u)
        for (let v = j, l = 0; l < 2; ++l, ++v)
            if (s[u][v] == '1')
                ++count;
    return count; }

function main() {
    for (let t = nextInt(); t > 0; --t) {
        const size = nextList();
        const n = size[0], m = size[1], p = n-1, q = m-1;
        let s = Array(n);
        for (let i = 0; i < n; ++i)
            s[i] = next();
        let elegant = true;
        for (let i = 0; i < p && elegant; ++i)
            for (let j = 0; j < q && elegant; ++j)
                elegant = ones_in_2x2(s,i,j) != 3;
        console.log(elegant? "YES": "NO"); } }

process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', line => { cin += line; });
process.stdin.on('end', _ => {
    cin = cin.trim().split('\n').map(line => { return line.trim(); });
    main(); });

'use strict'; /*jslint node:true, browser:true, es6:true*/
const print = console.log
const E = {};
const lines = []
if (!process.env.JEST_WORKER_ID){
  const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })
  rl.on('line', line => {
      lines.push(line);
  });
  rl.on('close', main)
}
let rli = 0;
function readline() {
    return lines[rli++];
}

module.exports = E;

const ra = ()=>readline().split(' ').map(a=>+a)

const EPS = 1e-6;

E.s2a = (arr)=>arr.map(a=>a.split('').map(c=>c=='0' ? 0 : 1))

let di = [0, 0, -1, 1]
let dj = [-1, 1, 0, 0]

const dfs = E.dfs = (arr, i, j)=>{
  if (arr[i][j]!=1)
    return [];
  let n = arr.length;
  let m = arr[0].length;
  let members = [];
  let q = [[i, j]], qi = 0;
  while (qi<q.length){
    let [ti, tj] = q[qi++];
    if (arr[ti][tj]==2)
      continue;
    arr[ti][tj] = 2;
    members.push([ti, tj]);
    for (let k=0; k<4; k++){
      let I = ti+di[k];
      let J = tj+dj[k];
      if (I<0 || J<0 || I>=n || J>=m)
        continue;
      if (arr[I][J]==1)
        q.push([I, J])
    }
  }
  return members;
};

const isFine = E.isFine = (members)=>{
  let minI = members[0][0]
  let maxI = members[0][0]
  let minJ = members[0][1]
  let maxJ = members[0][1]
  for (let [i, j] of members){
    minI = Math.min(minI, i);
    minJ = Math.min(minJ, j);
    maxI = Math.max(maxI, i);
    maxJ = Math.max(maxJ, j);
  }
  return (maxI-minI+1)*(maxJ-minJ+1)==members.length;
};

const calc = (arr)=>{
  arr = E.s2a(arr);
  let n = arr.length;
  let m = arr[0].length;
  for (let i=0; i<n; i++){
    for (let j=0; j<m; j++){
      let members = dfs(arr, i, j);
      if (members.length>0 && !isFine(members))
        return false;
    }
  }
  return true
};

function main() {
    let T = +readline();
    while (T--){
      let [n, m] = ra();
      let arr = [];
      for (let i=0;i<n;i++)
        arr.push(readline());
      print(calc(arr) ? 'yes' : 'no');
    }
}

E.calc = calc;

process.stdin.resume();
process.stdin.setEncoding("utf-8");

let inputString = "";
let currentLine = 0;

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});

process.stdin.on("end", (_) => {
  inputString = inputString
    .trim()
    .split("\n")
    .map((string) => {
      return string.trim();
    });

  main();
});

function readline() {
  return inputString[currentLine++];
}

function main() {
  const testCases = Number(readline());
  for (let t = 0; t < testCases; t++) {
    const [m, n] = readline().split(" ").map(Number);
    let board = [];

    for (let i = 0; i < m; i++) {
      let row = readline().split("").map(Number);
      board.push(row);
    }

    let broken = false;
    for (let i = 0; i < m; i++) {
      if (broken) break;
      for (let j = 0; j < n; j++) {
        if (board[i][j] === 1) {
          if (i !== 0) {
            if (j !== 0) {
              // check top left
              if (
                board[i][j - 1] === 1 &&
                board[i - 1][j] === 1 &&
                board[i - 1][j - 1] === 0
              ) {
                broken = true;
                break;
              }
            }

            if (j !== n - 1) {
              // check top right
              if (
                board[i][j + 1] === 1 &&
                board[i - 1][j] === 1 &&
                board[i - 1][j + 1] === 0
              ) {
                broken = true;
                break;
              }
            }
          }

          if (i !== m - 1) {
            if (j !== 0) {
              // check bottom left
              if (
                board[i][j - 1] === 1 &&
                board[i + 1][j] === 1 &&
                board[i + 1][j - 1] === 0
              ) {
                broken = true;
                break;
              }
            }

            if (j !== n - 1) {
              // check bottom right
              if (
                board[i][j + 1] === 1 &&
                board[i + 1][j] === 1 &&
                board[i + 1][j + 1] === 0
              ) {
                broken = true;
                break;
              }
            }
          }
        }
      }
    }

    if (broken) {
      console.log("NO");
    } else {
      console.log("YES");
    }
  }
}

function solve() {
   const [n, m] = readArray(Number);
   const matr = [];
   function get(x, y) {
      if (x < 0 || x >= n) {
         return '0';
      }
      if (y < 0 || y >= m) {
         return '0'
      }
      return matr[x][y];
   }
   for (let i = 0; i < n; i++) {
      matr.push(read().split(''));
   }
   for (let i = 0; i < n; i++) {
      for (let j = 0; j < m; j++) {
         if (get(i, j) === '0') {
            continue;
         }
         let i1 = i;
         while(get(i1, j) === '1') {
            i1++;
         }
         let j1 = j;
         while(get(i, j1) === '1') {
            j1++;
         }
         for (let x = i; x < i1; x++) {
            for (let y = j; y < j1; y++) {
               if (get(x, y) !== '1') {
                  write('NO');
                  return;
               }
               matr[x][y] = '0';
            }
         }
         for (let x = i; x < i1; x++) {
            if (get(x, j - 1) !== '0') {
               write('NO');
               return;
            }
            if (get(x, j1) !== '0') {
               write('NO');
               return;
            }
         }
         for (let y = j; y < j1; y++) {
            if (get(i - 1, y) !== '0') {
               write('NO');
               return;
            }
            if (get(i1, y) !== '0') {
               write('NO');
               return;
            }
         }
      }
   }
   write('YES');
}

function init() {
   try {
      var T = 1;
      T = Number(read());
      for (var t = 0; t < T; t++) {
         solve();
      }
   } catch (e) {
      write(e + e.stack);
   }
}

function modPow(a, n, mod) {
   let d = a;
   let curN = n;
   let ans = 1n;
   while(curN) {
      if (curN & 1n) {
         ans = modMul(ans, d, mod);
      }
      curN >>= 1n;
      d = modMul(d, d, mod);
   }
   return ans;
}

function modMul(a, b, mod) {
   return (a * b) % mod;
}

function modSum(a, b, mod) {
   return (a + b) % mod;
}

function modDiff(a, b, mod) {
   return (a + mod - b) % mod;
}

function isZero(num) {
   if (typeof num === 'bigint') {
      return num === 0n;
   }
   return num === 0;
}
function div(a, b) {
   if (typeof a !== typeof b) {
      throw new Error('Different types on division');
   }
   if (typeof a === 'bigint') {
      return a / b;
   }
   return Math.floor(a / b);
}

function gcd(x, y) {
   if (isZero(y)) {
      return x;
   }
   return gcd(y, x % y);
}

function lcm(x, y) {
   return div(x * y, gcd(x, y));
}

function allIndexOf(arr, value) {
   var index = arr.indexOf(value)
   var ans = [];
   while (index !== -1) {
      ans.push(index);
      index = arr.indexOf(value, index + 1);
   }
   return ans;
}

function xor(a, b, k) {
   if (k === 2) {
      return a ^ b;
   }
}

function decToBin(num) {
   let n = num;
   const ans = [];
   while(n > 0) {
      ans.push(n & 1);
      n = (n >> 1);
   }
   return ans;
}

function binToDec(binN) {
   let ans = 0;
   for (let i = binN.length - 1; i >= 0; i--) {
      ans = ((ans << 1) | binN[i]);
   }
   return ans;
}

function sortF(a, b) {
   if (a < b) {
      return -1;
   }
   if (a > b) {
      return 1;
   }
   return 0;
}

function readArray(f) {
   return read().split(' ').map(f);
}

var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');

   var path = require('path');

   var inTextName;
   var outTextName;

   var needWriteFile = false;

   var writeResult = '';
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
      init();
   }
} else {
   init();
}

function write(value) {
   if (needWriteFile) {
      writeResult += value + '\n';
      return;
   }
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   return isNode && MEMORY;
}

//const { readline, print } = require('@ip-algorithmics/codeforces-io');

function isBlack (array) {
  return !array.some(row => row.some(n => n !== 1))
}

function isWhite (array) {
  return !array.some(row => row.some(n => n !== 0))
}

function expand (array, i, j) {
  if (i >= array.length || i < 0 ||
  j < 0 || j >= array[0].length || array[i][j] !== 1) return;

  array[i][j] = 0;

  expand(array, i+1, j)
  expand(array, i-1, j)
  expand(array, i, j+1)
  expand(array, i, j-1)
}

var line = readline().split(' ').map(x => parseInt(x))
var testCases = line[0]

var n, m
while (testCases--) {
  line = readline().split(' ').map(x => parseInt(x))
  n = line[0]
  m = line[1]

  var array = new Array(n)

  for (var i = 0; i < n ; ++i) {
    array[i] = [];
    line = readline();

    for (var j = 0; j < line.length; ++j) {
      array[i].push(parseInt(line[j]));
    }
  }

  if (isBlack(array)) {
    print('YES')
    continue;
  }

  var elegantCount = 0;
  for (var i = 0; i < array.length; ++i) {
    for (var j = 0; j < array[i].length; ++j) {
      if (array[i][j] === 1) {
        expand(array, i, j);
        elegantCount++;
      }
    }
  }

  if (array.length=== 1 || array[0].length === 1) {
    print ('YES')
  } else
    print (elegantCount > 1 ? 'YES' : 'NO')
}

//const { readline, print } = require('@ip-algorithmics/codeforces-io');

function isBlack (array) {
  return !array.some(row => row.some(n => n !== 1))
}

function expand (array, i, j) {
  if (i >= array.length || i < 0 ||
  j < 0 || j >= array[0].length || array[i][j] !== 1) return;

  array[i][j] = 0;

  expand(array, i+1, j)
  expand(array, i-1, j)
  expand(array, i, j+1)
  expand(array, i, j-1)
}

var line = readline().split(' ').map(x => parseInt(x))
var testCases = line[0]

var n, m
while (testCases--) {
  line = readline().split(' ').map(x => parseInt(x))
  n = line[0]
  m = line[1]

  var array = new Array(n)

  for (var i = 0; i < n ; ++i) {
    array[i] = [];
    line = readline();

    for (var j = 0; j < line.length; ++j) {
      array[i].push(parseInt(line[j]));
    }
  }

  if (isBlack(array)) {
    print('YES')
    continue;
  }

  var elegantCount = 0;
  for (var i = 0; i < array.length; ++i) {
    for (var j = 0; j < array[i].length; ++j) {
      if (array[i][j] === 1) {
        expand(array, i, j);
        elegantCount++;
      }
    }
  }

  if (array.length=== 1 || array[0].length === 1) {
    print ('YES')
  } else
    print (elegantCount > 1 ? 'YES' : 'NO')
}

// const { readline, print } = require('@ip-algorithmics/codeforces-io');

function expand (array, i, j) {
  if (i >= array.length || i < 0 ||
  j < 0 || j >= array[0].length || array[i][j] !== 1) return;

  array[i][j] = 0;

  expand(array, i+1, j)
  expand(array, i-1, j)
  expand(array, i, j+1)
  expand(array, i, j-1)
}

var line = readline().split(' ').map(x => parseInt(x))
var testCases = line[0]

var n, m
while (testCases--) {
  line = readline().split(' ').map(x => parseInt(x))
  n = line[0]
  m = line[1]

  var array = new Array(n)

  for (var i = 0; i < n ; ++i) {
    array[i] = [];
    line = readline();

    for (var j = 0; j < line.length; ++j) {
      array[i].push(parseInt(line[j]));
    }
  }

  var elegantCount = 0;
  for (var i = 0; i < array.length; ++i) {
    for (var j = 0; j < array[i].length; ++j) {
      if (array[i][j] === 1) {
        expand(array, i, j);
        elegantCount++;
      }
    }
  }

  if (array.length=== 1 || array[0].length === 1) {
    print ('YES')
  } else
    print (elegantCount > 1 ? 'YES' : 'NO')
}

var tests = parseInt(readline());
    var n,m;
    var mat;
    var visited;

    function checkSquare(i, j) {
        visited[i][j] = 1;
        var col = j;
        while (col < m && mat[i][col]) {
            col++;
            visited[i][col] = 1;
        }
        var width = col - j;

        var row = i+1;
        while (row < n && mat[row][j]) {
            col = j;
            while (col < j + width) {
                visited[row][col] = 1;
                if (!mat[row][col]) {
                    return false;
                }
                col++;
            }
            visited[row][col] = 1;
            if (mat[row][col]) {
                return false;
            }
            row++;
        }
        if (row < n) {
            for (var c = j; c < j + width; c++) {
                visited[row][c] = 1;
                if (mat[row][c]) {
                    return false;
                }
            }
        }

        return true;
    }

    for (var t=0; t < tests; t++) {
        var nm = readline().split(' ').map(x=>parseInt(x));
        n = nm[0];
        m = nm[1];
        mat = [];
        visited = [];
        for (var i = 0; i < n; i++) {
            mat.push(readline().split('').map(x=>parseInt(x)));
            visited.push(new Array(m).fill(0));
        }

        var ans = 'YES';
        for (var i = 0; i < n; i++) {
            for (var j = 0; j < m; j++) {
                if (visited[i][j]) {
                    continue;
                }
                if (!mat[i][j]) {
                    visited[i][j] = 1;
                    continue;
                }
                if (checkSquare(i, j)) {
                    continue;
                }
                ans = 'NO';
            }
        }
        print(ans);
    }

"use strict";

process.stdin.resume();
process.stdin.setEncoding("utf-8");

let inputStr = "";
let currentLne = 0;

process.stdin.on('data' , inputStdin =>{

	 inputStr += inputStdin;
})

process.stdin.on('end' , _ =>{
    inputStr = inputStr.trim().split('\n').map( string =>{
    	return string.trim();
    })

main();
})

function readline(){
   return inputStr[currentLne++];
}

function main(){

    let t = parseInt(readline());
    let c= 0;
    while(c<t){

      let m = readline().split(" ").map(a =>parseInt(a));
      let m0 = m[0];
      let countRow = 0 ;
      let arr =[];
      while(countRow < m0){
        let row = readline().split("").map(b=>parseInt(b));
        arr.push(row);
        countRow++;
      }

    let eleg =true;
    let count =0;
    // for (var k = 0; k < arr.length; k++) {
    //     if(arr[k].indexOf(1) == -1 ){
    //          count++;
    //     }
    // }

    for (var i = 0; i < arr.length-1; i++) {

        for (var j = 0; j < arr[0].length; j++) {

          if(arr[i][j] ==1){
               if(j !==0 && arr[i+1][j] ==1 && arr[i+1][j-1] ==1 && arr[i][j-1] ==0 ){
                    eleg= false;
                    // console.log(i,j,"1st")
                    break;
               }

               if(arr[i+1][j]==1 && arr[i+1][j+1] ==1 && arr[i][j+1] == 0){
                   eleg =false;
                    // console.log(i,j,"2st")
                    break;
               }

               if(arr[i][j+1]==1 && arr[i+1][j]==1 && arr[i+1][j+1] ==0){
                eleg = false;
                 // console.log(i,j,"3st")
                 break;
               }

               if(i !== 0 && arr[i][j+1]==1 && arr[i-1][j] == 1 && arr[i-1][j-1] == 0){
                eleg =false;
                 // console.log(i,j,"4st")
                 break;
               }

               if(arr[i][j+1]==1 && arr[i+1][j+1] ==1 && arr[i+1][j]==0){
                eleg =false;
                // console.log(i,j,"5st")
                break;
               }
          }
        }

    }

    // if(count == arr.length*arr[0].length ){
    //     eleg = false;
    // }

    if(eleg){
        console.log("yes");
    }else{
        console.log("no");
    }

    c++;
    }

}

//type input.txt | node code.js

"use strict";

process.stdin.resume();
process.stdin.setEncoding("utf-8");

let inputStr = "";
let currentLne = 0;

process.stdin.on('data' , inputStdin =>{

	 inputStr += inputStdin;
})

process.stdin.on('end' , _ =>{
    inputStr = inputStr.trim().split('\n').map( string =>{
    	return string.trim();
    })

main();
})

function readline(){
   return inputStr[currentLne++];
}

function main(){

    let t = parseInt(readline());
    let c= 0;
    while(c<t){

      let m = readline().split(" ").map(a =>parseInt(a));
      let m0 = m[0];
      let countRow = 0 ;
      let arr =[];
      while(countRow < m0){
        let row = readline().split("").map(b=>parseInt(b));
        arr.push(row);
        countRow++;
      }

    let eleg =true;
    let count =0;
    // for (var k = 0; k < arr.length; k++) {
    //     if(arr[k].indexOf(1) == -1 ){
    //          count++;
    //     }
    // }

    for (var i = 0; i < arr.length-1; i++) {

        for (var j = 0; j < arr[0].length-1; j++) {

          if(arr[i][j] ==1){
               if(j !==0 && arr[i+1][j] ==1 && arr[i+1][j-1] ==1 && arr[i][j-1] ==0 ){
                    eleg= false;
                    // console.log(i,j,"1st")
                    break;
               }

               if(arr[i+1][j]==1 && arr[i+1][j+1] ==1 && arr[i][j+1] == 0){
                   eleg =false;
                    // console.log(i,j,"2st")
                    break;
               }

               if(arr[i][j+1]==1 && arr[i+1][j]==1 && arr[i+1][j+1] ==0){
                eleg = false;
                 // console.log(i,j,"3st")
                 break;
               }

               if(i !== 0 && arr[i][j+1]==1 && arr[i-1][j] == 1 && arr[i-1][j-1] == 0){
                eleg =false;
                 // console.log(i,j,"4st")
                 break;
               }

               if(arr[i][j+1]==1 && arr[i+1][j+1] ==1 && arr[i+1][j]==0){
                eleg =false;
                // console.log(i,j,"5st")
                break;
               }
          }
        }

    }

    // if(count == arr.length*arr[0].length ){
    //     eleg = false;
    // }

    if(eleg){
        console.log("yes");
    }else{
        console.log("no");
    }

    c++;
    }

}

//type input.txt | node code.js

"use strict";

process.stdin.resume();
process.stdin.setEncoding("utf-8");

let inputStr = "";
let currentLne = 0;

process.stdin.on('data' , inputStdin =>{

	 inputStr += inputStdin;
})

process.stdin.on('end' , _ =>{
    inputStr = inputStr.trim().split('\n').map( string =>{
    	return string.trim();
    })

main();
})

function readline(){
   return inputStr[currentLne++];
}

function main(){

    let t = parseInt(readline());
    let c= 0;
    while(c<t){

      let m = readline().split(" ").map(a =>parseInt(a));
      let m0 = m[0];
      let countRow = 0 ;
      let arr =[];
      while(countRow < m0){
        let row = readline().split("").map(b=>parseInt(b));
        arr.push(row);
        countRow++;
      }

    let eleg =true;
    let count =0;
    // for (var k = 0; k < arr.length; k++) {
    //     if(arr[k].indexOf(1) == -1 ){
    //          count++;
    //     }
    // }

    for (var i = 0; i < arr.length-1; i++) {

        for (var j = 0; j < arr[0].length-1; j++) {

            if(arr[i][j] ==1){
               if(j !==0 && arr[i+1][j] ==1 && arr[i+1][j-1] ==1 && arr[i][j-1] ==0 ){
                    eleg= false;
               }

               if(arr[i+1][j]==1 && arr[i+1][j+1] ==1 && arr[i][j+1] == 0){
                   eleg =false;
               }

               if(arr[i][j+1]==1 && arr[i+1][j]==1 && arr[i+1][j+1] ==0){
                eleg = false;
               }

               if(i !== 0 && arr[i][j+1]==1 && arr[i-1][j] == 1 && arr[i+1][j+1] == 0){
                eleg =false;
               }

               if(arr[i][j+1]==1 && arr[i+1][j+1] ==1 && arr[i+1][j]==0){
                eleg =false;
               }
          }
        }

    }

    // if(count == arr.length*arr[0].length ){
    //     eleg = false;
    // }

    if(eleg){
        console.log("yes");
    }else{
        console.log("no");
    }

    c++;
    }

}

//type input.txt | node code.js

"use strict";

process.stdin.resume();
process.stdin.setEncoding("utf-8");

let inputStr = "";
let currentLne = 0;

process.stdin.on('data' , inputStdin =>{

	 inputStr += inputStdin;
})

process.stdin.on('end' , _ =>{
    inputStr = inputStr.trim().split('\n').map( string =>{
    	return string.trim();
    })

main();
})

function readline(){
   return inputStr[currentLne++];
}

function main(){

    let t = parseInt(readline());
    let c= 0;
    while(c<t){

      let m = readline().split(" ").map(a =>parseInt(a));
      let m0 = m[0];
      let countRow = 0 ;
      let arr =[];
      while(countRow < m0){
        let row = readline().split("").map(b=>parseInt(b));
        arr.push(row);
        countRow++;
      }

    let eleg =true;
    let count =0;
    // for (var k = 0; k < arr.length; k++) {
    //     if(arr[k].indexOf(1) == -1 ){
    //          count++;
    //     }
    // }

    for (var i = 0; i < arr.length-1; i++) {

        for (var j = 0; j < arr[0].length-1; j++) {

            if(arr[i][j] ==1 && arr[i][j+1] ==1){
            if((arr[i+1][j] == 1 && arr[i+1][j+1] == 0 ) ||  (arr[i+1][j] == 0 && arr[i+1][j+1] == 1 ) ){
                  eleg =false;
                }

                if( j !==0){
                if(arr[i][j-1] == 0 && arr[i+1][j-1] ==1 && arr[i+1][j] ==1 ){
                   eleg =false;
                }
                }

                if(i !==0 ){
                if((arr[i-1][j+1] ==1 && arr[i-1][j]==0) || (arr[i-1][j+1] ==0 && arr[i-1][j]==1)){
                    eleg =false;
                }
            }
            }
        }

    }

    // if(count == arr.length*arr[0].length ){
    //     eleg = false;
    // }

    if(eleg){
        console.log("yes");
    }else{
        console.log("no");
    }

    c++;
    }

}

//type input.txt | node code.js

"use strict";

process.stdin.resume();
process.stdin.setEncoding("utf-8");

let inputStr = "";
let currentLne = 0;

process.stdin.on('data' , inputStdin =>{

	 inputStr += inputStdin;
})

process.stdin.on('end' , _ =>{
    inputStr = inputStr.trim().split('\n').map( string =>{
    	return string.trim();
    })

main();
})

function readline(){
   return inputStr[currentLne++];
}

function main(){

    let t = parseInt(readline());
    let c= 0;
    while(c<t){

      let m = readline().split(" ").map(a =>parseInt(a));
      let m0 = m[0];
      let countRow = 0 ;
      let arr =[];
      while(countRow < m0){
        let row = readline().split("").map(b=>parseInt(b));
        arr.push(row);
        countRow++;
      }

    let eleg =true;
    let count =0;
    // for (var k = 0; k < arr.length; k++) {
    //     if(arr[k].indexOf(1) == -1 ){
    //          count++;
    //     }
    // }

    for (var i = 0; i < arr.length-1; i++) {

        for (var j = 0; j < arr[0].length-1; j++) {

            if(arr[i][j] ==1 && arr[i][j+1] ==1){
            if((arr[i+1][j] == 1 && arr[i+1][j+1] == 0 ) ||  (arr[i+1][j] == 0 && arr[i+1][j+1] == 1 ) ){
                  eleg =false;
                }

                if( j !==0){
                if(arr[i][j-1] == 0 && arr[i+1][j-1] ==1 && arr[i+1][j] ==1 ){
                   eleg =false;
                }
                }
            }
        }

    }

    // if(count == arr.length*arr[0].length ){
    //     eleg = false;
    // }

    if(eleg){
        console.log("yes");
    }else{
        console.log("no");
    }

    c++;
    }

}

//type input.txt | node code.js

"use strict";

process.stdin.resume();
process.stdin.setEncoding("utf-8");

let inputStr = "";
let currentLne = 0;

process.stdin.on('data' , inputStdin =>{

	 inputStr += inputStdin;
})

process.stdin.on('end' , _ =>{
    inputStr = inputStr.trim().split('\n').map( string =>{
    	return string.trim();
    })

main();
})

function readline(){
   return inputStr[currentLne++];
}

function main(){

    let t = parseInt(readline());
    let c= 0;
    while(c<t){

      let m = readline().split(" ").map(a =>parseInt(a));
      let m0 = m[0];
      let countRow = 0 ;
      let arr =[];
      while(countRow < m0){
        let row = readline().split("").map(b=>parseInt(b));
        arr.push(row);
        countRow++;
      }

    let eleg =true;
    let count =0;
    // for (var k = 0; k < arr.length; k++) {
    //     if(arr[k].indexOf(1) == -1 ){
    //          count++;
    //     }
    // }

    for (var i = 0; i < arr.length-1; i++) {

        for (var j = 0; j < arr[0].length-1; j++) {

            if(arr[i][j] ==1 && arr[i][j+1] ==1){
                if(arr[i+1][j] == 1 && arr[i+1][j+1] == 0){
                  eleg =false;
                }

                if( j !==0){
                  if(arr[i][j-1] == 0 && arr[i+1][j-1] ==1 ){
                   eleg =false;
                }
                }
            }
        }

    }

    // if(count == arr.length*arr[0].length ){
    //     eleg = false;
    // }

    if(eleg){
        console.log("yes");
    }else{
        console.log("no");
    }

    c++;
    }

}

//type input.txt | node code.js

"use strict";

process.stdin.resume();
process.stdin.setEncoding("utf-8");

let inputStr = "";
let currentLne = 0;

process.stdin.on('data' , inputStdin =>{

	 inputStr += inputStdin;
})

process.stdin.on('end' , _ =>{
    inputStr = inputStr.trim().split('\n').map( string =>{
    	return string.trim();
    })

main();
})

function readline(){
   return inputStr[currentLne++];
}

function main(){

    let t = parseInt(readline());
    let c= 0;
    while(c<t){

      let m = readline().split(" ").map(a =>parseInt(a));
      let m0 = m[0];
      let countRow = 0 ;
      let arr =[];
      while(countRow < m0){
        let row = readline().split("").map(b=>parseInt(b));
        arr.push(row);
        countRow++;
      }

    let eleg =true;
    let count =0;
    for (var k = 0; k < arr.length; k++) {
        if(arr[k].indexOf(1) == -1 ){
             count++;
        }
    }

    for (var i = 0; i < arr.length-1; i++) {

        for (var j = 0; j < arr[0].length-1; j++) {

            if(arr[i][j] ==1 && arr[i][j+1] ==1){
                if(arr[i+1][j] == 1 && arr[i+1][j+1] == 0){
                  eleg =false;
                }

                if( j !==0){
                  if(arr[i][j-1] == 0 && arr[i+1][j-1] ==1 ){
                   eleg =false;
                }
                }
            }
        }

    }

    if(count == arr.length*arr[0].length ){
        eleg = false;
    }

    if(eleg){
        console.log("yes");
    }else{
        console.log("no");
    }

    c++;
    }

}

//type input.txt | node code.js

"use strict";

process.stdin.resume();
process.stdin.setEncoding("utf-8");

let inputStr = "";
let currentLne = 0;

process.stdin.on('data' , inputStdin =>{

	 inputStr += inputStdin;
})

process.stdin.on('end' , _ =>{
    inputStr = inputStr.trim().split('\n').map( string =>{
    	return string.trim();
    })

main();
})

function readline(){
   return inputStr[currentLne++];
}

function main(){

    let t = parseInt(readline());
    let c= 0;
    while(c<t){

      let m = readline().split(" ").map(a =>parseInt(a));
      let m0 = m[0];
      let countRow = 0 ;
      let arr =[];
      while(countRow < m0){
        let row = readline().split("").map(b=>parseInt(b));
        arr.push(row);
        countRow++;
      }

    let eleg =true;
    let count =0;
    for (var k = 0; k < arr.length; k++) {
        if(arr[k].indexOf(1) == -1 ){
             count++;
        }
    }

    for (var i = 0; i < arr.length-1; i++) {

        for (var j = 0; j < arr[0].length-1; j++) {

            if(arr[i][j] ==1 && arr[i][j+1] ==1){
                if(arr[i+1][j] == 1 && arr[i+1][j+1] == 0){
                  eleg =false;
                }

                if( j !==0){
                  if(arr[i][j-1] == 0 && arr[i+1][j-1] ==1 ){
                   eleg =false;
                }
                }
            }
        }

    }

    if(count == arr.length){
        eleg = false;
    }

    if(eleg){
        console.log("yes");
    }else{
        console.log("no");
    }

    c++;
    }

}

//type input.txt | node code.js

"use strict";

process.stdin.resume();
process.stdin.setEncoding("utf-8");

let inputStr = "";
let currentLne = 0;

process.stdin.on('data' , inputStdin =>{

	 inputStr += inputStdin;
})

process.stdin.on('end' , _ =>{
    inputStr = inputStr.trim().split('\n').map( string =>{
    	return string.trim();
    })

main();
})

function readline(){
   return inputStr[currentLne++];
}

function main(){

    let t = parseInt(readline());
    let c= 0;
    while(c<t){

      let m = readline().split(" ").map(a =>parseInt(a));
      let m0 = m[0];
      let countRow = 0 ;
      let arr =[];
      while(countRow < m0){
        let row = readline().split("").map(b=>parseInt(b));
        arr.push(row);
        countRow++;
      }

    let eleg =true;
    let count =0;
    for (var i = 0; i < arr.length-1; i++) {

        for (var j = 0; j < arr[0].length-1; j++) {

           if(arr[i][j] == 0 && arr[i][j+1]==0 ){
              if(arr[i+1][j] == 0 && arr[i+1][j+1] == 0){
                  count++;
                }
           }

            if(arr[i][j] ==1 && arr[i][j+1] ==1){
                if(arr[i+1][j] == 1 && arr[i+1][j+1] == 0){
                  eleg =false;
                }

                if( j !==0){
                  if(arr[i][j-1] == 0 && arr[i+1][j-1] ==1 ){
                   eleg =false;
                }
                }
            }
        }

    }
    let tot = Math.floor(((arr.length * arr[0].length)-1)/2);
    //console.log(count,tot)
    if(count == tot){
    eleg =false;
    }

    if(eleg){
        console.log("yes");
    }else{
        console.log("no");
    }

    c++;
    }

}

//type input.txt | node code.js

"use strict";

process.stdin.resume();
process.stdin.setEncoding("utf-8");

let inputStr = "";
let currentLne = 0;

process.stdin.on('data' , inputStdin =>{

	 inputStr += inputStdin;
})

process.stdin.on('end' , _ =>{
    inputStr = inputStr.trim().split('\n').map( string =>{
    	return string.trim();
    })

main();
})

function readline(){
   return inputStr[currentLne++];
}

function main(){

    let t = parseInt(readline());
    let c= 0;
    while(c<t){

      let m = readline().split(" ").map(a =>parseInt(a));
      let m0 = m[0];
      let countRow = 0 ;
      let arr =[];
      while(countRow < m0){
        let row = readline().split("").map(b=>parseInt(b));
        arr.push(row);
        countRow++;
      }

    let eleg =true;
    for (var i = 0; i < arr.length-1; i++) {

        for (var j = 0; j < arr[0].length; j++) {
            if(arr[i][j] ==1 && arr[i][j+1] ==1){
                if(arr[i+1][j] == 1 && arr[i+1][j+1] == 0){
                  eleg =false;
                }

                if( j !==0){
                  if(arr[i][j-1] == 0 && arr[i+1][j-1] ==1 ){
                   eleg =false;
                }
                }
            }
        }

    }
    if(eleg){
        console.log("yes");
    }else{
        console.log("no");
    }

    c++;
    }

}

//type input.txt | node code.js

"use strict";

process.stdin.resume();
process.stdin.setEncoding("utf-8");

let inputStr = "";
let currentLne = 0;

process.stdin.on('data' , inputStdin =>{

	 inputStr += inputStdin;
})

process.stdin.on('end' , _ =>{
    inputStr = inputStr.trim().split('\n').map( string =>{
    	return string.trim();
    })

main();
})

function readline(){
   return inputStr[currentLne++];
}

function main(){

    let t = parseInt(readline());
    let c= 0;
    while(c<t){

      let m = readline().split(" ").map(a =>parseInt(a));
      let m0 = m[0];
      let countRow = 0 ;
      let arr =[];
      while(countRow < m0){
        let row = readline().split("").map(b=>parseInt(b));
        arr.push(row);
        countRow++;
      }

    let eleg =true;
    for (var i = 0; i < arr.length-1; i++) {

        for (var j = 0; j < arr[0].length; j++) {
            if(arr[i][j] ==1 && arr[i][j+1] ==1){
                if(arr[i+1][j] == 1 && arr[i+1][j+1] == 0){
                  eleg =false;
                }
            }
        }

    }
    if(eleg){
        console.log("yes");
    }else{
        console.log("no");
    }

    c++;
    }

}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let [n, m] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr = [];
    for (let i = 0; i < n; i++)
      arr.push(
        readline()
          .trim()
          .split("")
          .map((cur) => parseInt(cur))
      );
    if (n === 1) {
      let ans = false;
      for (let i = 0; i < m; i++) {
        if (arr[0][i] === 1) {
          ans = true;
          break;
        }
      }
      console.log(`${ans === true ? "YES" : "NO"}`);
      continue;
    }
    if (m === 1) {
      let ans = false;
      for (let i = 0; i < n; i++) {
        if (arr[i][0] === 1) {
          ans = true;
          break;
        }
      }
      console.log(`${ans === true ? "YES" : "NO"}`);
      continue;
    }
    const ne = (r, c, n, m) => {
      let arr1 = [];
      if (r !== n - 1 && arr[r + 1][c] === 1) arr1.push([r + 1, c]);
      if (r !== 0 && arr[r - 1][c] === 1) arr1.push([r - 1, c]);
      if (c !== 0 && arr[r][c - 1] === 1) arr1.push([r, c - 1]);
      if (c !== m - 1 && arr[r][c + 1] === 1) arr1.push([r, c + 1]);
      return arr1;
    };
    const dfs = (row, col, m, n) => {
      let obj = {};
      const helper = (row, col) => {
        arr[row][col] = 0;
        obj[[row, col]] = 1;
        let neigh = ne(row, col, n, m);
        for (let i of neigh) if (!obj[(i[0], i[1])]) helper(i[0], i[1]);
      };
      helper(row, col);
    };
    let ist = false,
      ans = false;
    for (let i = 0; i < n; i++) {
      for (let j = 0; j < m; j++) {
        if (arr[i][j] === 1) {
          if (ist) {
            ans = true;
            break;
          }
          dfs(i, j, m, n);
          ist = true;
        }
      }
      if (ans) break;
    }
    if (ans && ist) console.log("YES");
    else if (ist) console.log("NO");
    else console.log("YES");
  }
};
solve();

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let [n, m] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr = [];
    for (let i = 0; i < n; i++)
      arr.push(
        readline()
          .trim()
          .split("")
          .map((cur) => parseInt(cur))
      );
    if (n === 1) {
      let ans = false;
      for (let i = 0; i < m; i++) {
        if (arr[0][i] === 1) {
          ans = true;
          break;
        }
      }
      console.log(`${ans === true ? "YES" : "NO"}`);
      continue;
    }
    const ne = (r, c, n, m) => {
      let arr1 = [];
      if (r !== n - 1 && arr[r + 1][c] === 1) arr1.push([r + 1, c]);
      if (r !== 0 && arr[r - 1][c] === 1) arr1.push([r - 1, c]);
      if (c !== 0 && arr[r][c - 1] === 1) arr1.push([r, c - 1]);
      if (c !== m - 1 && arr[r][c + 1] === 1) arr1.push([r, c + 1]);
      return arr1;
    };
    const dfs = (row, col, m, n) => {
      let obj = {};
      const helper = (row, col) => {
        arr[row][col] = 0;
        obj[[row, col]] = 1;
        let neigh = ne(row, col, n, m);
        for (let i of neigh) if (!obj[(i[0], i[1])]) helper(i[0], i[1]);
      };
      helper(row, col);
    };
    let ist = false,
      ans = false;
    for (let i = 0; i < n; i++) {
      for (let j = 0; j < m; j++) {
        if (arr[i][j] === 1) {
          if (ist) {
            ans = true;
            break;
          }
          dfs(i, j, m, n);
          ist = true;
        }
      }
      if (ans) break;
    }
    console.log(`${ans === true ? "YES" : "NO"}`);
  }
};
solve();

'use strict';

var readline = require('readline');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, m, s) {
  const sum = Array.from({
    length: n
  }, () => new Array(m).fill(0));
  for (let i = 0; i < n; i++) {
    for (let j = 0; j < m; j++) {
      var _sum$j, _sum, _sum$i, _sum2, _sum3;
      sum[i][j] = ((_sum$j = (_sum = sum[i - 1]) === null || _sum === void 0 ? void 0 : _sum[j]) !== null && _sum$j !== void 0 ? _sum$j : 0) + ((_sum$i = sum[i][j - 1]) !== null && _sum$i !== void 0 ? _sum$i : 0) - ((_sum2 = (_sum3 = sum[i - 1]) === null || _sum3 === void 0 ? void 0 : _sum3[j - 1]) !== null && _sum2 !== void 0 ? _sum2 : 0) + Number(s[i][j]);
    }
  }
  const p = [...new Array(n * m).keys()];
  const find = i => {
    if (p[i] !== i) p[i] = find(p[p[i]]);
    return p[i];
  };
  const union = (i, j) => {
    const ri = find(i),
          rj = find(j);
    if (ri !== rj) p[rj] = ri;
  };
  const dirs = [[0, 1], [1, 0]];
  for (let i = 0; i < n; i++) {
    for (let j = 0; j < m; j++) {
      const a = i * m + j;
      if (s[i][j] === '0') {
        p[a] = -1;
        continue;
      }
      for (let [di, dj] of dirs) {
        const ni = di + i,
              nj = dj + j,
              b = ni * m + nj;
        if (ni < 0 || ni >= n || nj < 0 || nj >= m || s[ni][nj] === '0') continue;
        union(a, b);
      }
    }
  }
  const scc = new Map();
  for (let [i, num] of p.entries()) {
    if (num === -1) continue;
    const root = find(num);
    if (!scc.has(root)) scc.set(root, []);
    scc.get(root).push(i);
  }
  for (let [, points] of scc) {
    var _sum$rb, _sum$rr, _sum4, _sum5, _sum6;
    let ll = Infinity,
        lt = Infinity,
        rr = -Infinity,
        rb = -Infinity;
    for (let num of points) {
      const i = Math.floor(num / m),
            j = num % m;
      ll = Math.min(ll, i);
      lt = Math.min(lt, j);
      rr = Math.max(rr, j);
      rb = Math.max(rb, i);
    }
    if (sum[rb][rr] - ((_sum$rb = sum[rb][ll - 1]) !== null && _sum$rb !== void 0 ? _sum$rb : 0) - ((_sum$rr = (_sum4 = sum[lt - 1]) === null || _sum4 === void 0 ? void 0 : _sum4[rr]) !== null && _sum$rr !== void 0 ? _sum$rr : 0) + ((_sum5 = (_sum6 = sum[lt - 1]) === null || _sum6 === void 0 ? void 0 : _sum6[ll - 1]) !== null && _sum5 !== void 0 ? _sum5 : 0) !== (rr - ll + 1) * (rb - lt + 1)) return 'NO';
  }
  return 'YES';
}

async function main(read) {
  let t = Number(await read());
  let res = [];
  while (t--) {
    const [n, m] = (await read()).split(' ').map(Number);
    const a = [];
    let tmp = n;
    while (tmp--) {
      a.push(await read());
    }
    res.push(solve(n, m, a));
  }
  console.log(res.join('\n'));
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();


A string t is called an anagram of the string s, if it is possible to rearrange letters in t so that it is identical to the string s. For example, the string "aab" is an anagram of the string "aba" and the string "aaa" is not.The string t is called a substring of the string s if it can be read starting from some position in the string s. For example, the string "aba" has six substrings: "a", "b", "a", "ab", "ba", "aba".You are given a string s, consisting of lowercase Latin letters and characters "?". You are also given a string p, consisting of lowercase Latin letters only. Let's assume that a string is good if you can obtain an anagram of the string p from it, replacing the "?" characters by Latin letters. Each "?" can be replaced by exactly one character of the Latin alphabet. For example, if the string p = «aba», then the string "a??" is good, and the string «?bc» is not. Your task is to find the number of good substrings of the string s (identical substrings must be counted in the answer several times).

The first line is non-empty string s, consisting of no more than 105 lowercase Latin letters and characters "?". The second line is non-empty string p, consisting of no more than 105 lowercase Latin letters. Please note that the length of the string p can exceed the length of the string s.

Print the single number representing the number of good substrings of string s. Two substrings are considered different in their positions of occurrence are different. Thus, if some string occurs several times, then it should be counted the same number of times.

NoteConsider the first sample test. Here the string s has two good substrings: "b??" (after we replace the question marks we get "baa"), "???" (after we replace the question marks we get "baa").Let's consider the second sample test. Here the string s has two good substrings: "ab?" ("?" can be replaced by "c"), "b?c" ("?" can be replaced by "a").

print(function(s, p) {
	var A = 'a'.charCodeAt();
	var a = new Uint32Array(26);
	var b = new Uint32Array(26);
	var ans = 0;

	for (var i = 0; i < p.length; i++)
		a[p.charCodeAt(i) - A]++;

	var c = 0;
	for (var j = 0; j < s.length; j++) {
		if (s[j] === '?')
			c++;
		else
			b[s.charCodeAt(j) - A]++;

		var l = j - p.length;
		if (l >= 0) {
			if (s[l] === '?')
				c--;
			else
				b[s.charCodeAt(l) - A]--;
		}
		if (e())
			ans++;
	}

	return ans;

	function e() {
		var ret = 0;
		for (var i = 0; i < 26; i++)
			if (a[i] > 0 && a[i] - b[i] > 0)
				ret += a[i] - b[i];
		return ret === c;
	}
}(readline(), readline()));


There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.

The first line contains two integers a, b (1 ≤ a, b ≤ 1000), separated by a single space.

In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers — the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.

function trim(s) {
	return s.replace(/^\s+|\s+$/gm, '');
}

function tokenize(s) {
	return trim(s).split(/\s+/);
}

function tokenizeIntegers(s) {
	var tokens = tokenize(s);
	for (var i = 0; i < tokens.length; i += 1) {
		tokens[i] = parseInt(tokens[i], 10);
	};
	return tokens;
}

function main() {
	var data = tokenizeIntegers(readline()),
		a = data[0], b = data[1],
		a2 = a*a;
	for (var y = 1; y*y < a2; ++y) {
		var x = Math.sqrt(a2 - y*y);
		if (x == Math.floor(x)) {
			if ((b*y)%a == 0 && (b*x)%a == 0 && x != b*y/a) {
				print('YES');
				print(0, 0);
				print(x, y);
				print(b*y/a, b*-x/a);
				return;
			}
		}
	}
	print('NO');
}

main();

function trim(s) {
	return s.replace(/^\s+|\s+$/gm, '');
}

function tokenize(s) {
	return trim(s).split(/\s+/);
}

function tokenizeIntegers(s) {
	var tokens = tokenize(s);
	for (var i = 0; i < tokens.length; i += 1) {
		tokens[i] = parseInt(tokens[i], 10);
	};
	return tokens;
}

function main() {
	var data = tokenizeIntegers(readline()),
		a = data[0], b = data[1],
		a2 = a*a;
	for (var y = 1; 2*y*y <= a2; ++y) {
		var x = Math.sqrt(a2 - y*y);
		if (x == Math.floor(x)) {
			if ((b*y)%a == 0 && (b*x)%a == 0 && x != b*y/a) {
				print('YES');
				print(0, 0);
				print(x, y);
				print(b*y/a, b*-x/a);
				return;
			}
		}
	}
	print('NO');
}

main();


You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i < n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.

For each test case, output the answer on a new line.

NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.

const main = () => {

	var t = readInt();
	var allans = [];
	for (var zz = 0; zz < t; zz++) {
		var n = readInt();
		var a = readIntArr();
		var b;

		// there won't be too many moves before most/everyone becomes 0
		var ans = 0;
		var zerocnt = 0;
		while (a.length > 1) {
			a.sort((x, y) => (y - x)); // sort descending
			while (a.length > 1 && a[a.length - 1] === 0) {
				zerocnt++;
				a.pop();
			}
			if (zerocnt > 0 && a.length > 0 && a[a.length - 1] !== 0) {
				a.push(0);
				zerocnt--;
			}
			b = [];
			for (var i  = 1; i < a.length; i++)
				b.push(a[i - 1] - a[i]);
			a = b;
		}
		if (a.length === 1)
			ans = a[0];
		allans.push(ans);
	}
	multiLineArrayPrint(allans);

	return;
}

const readInt = () => parseInt(readline());
const readString = () => readline();
const readIntArr = () => readline().split(" ").map(zzzz => parseInt(zzzz));
const parseLong = (string) => { // javascript's largest long is < (1<<62)
	var n = string.length;
	var res = 0;
	for (var i = 0; i < n; i++) {
		res *= 10;
		res += parseInt(string[i]);
	}
	return res;
}
const readLong = () => parseLong(readLong());
const readLongArr = () => readline().split(" ").map(zzzz => parseLong(zzzz));
const oneLineArrayPrint = (arr) => print(arr.map(zzzz => zzzz.toString()).join(' '));
const multiLineArrayPrint = (arr) => print(arr.map(zzzz => zzzz.toString()).join('\n'));
const multiLineArrayOfArraysPrint = (arr) => print(arr.map(yyyy => yyyy.map(zzzz => zzzz.toString()).join(' ')).join('\n'));
const makeArr = (defaultVal, dimensionsArr) => {
	var n = dimensionsArr.length;
	if (n === 1) return Array(dimensionsArr[0]).fill(defaultVal);
	else {
		var temp = [];
		for (var i = 0; i < dimensionsArr[0]; i++)
			temp.push(makeArr(defaultVal, dimensionsArr.slice(1)));
		return temp;
	}
}

for (_ = 0; _ < 1; _++) {
	main();
}

// newline for testing
 //newline for testing
// codeforces js cannot use "let" keyword. use "var" instead
// codeforces js cannot destructure arrays

'use strict';

function solve(n, a) {
  for (let len = n - 1; len > 0; len--) {
    const b = [];
    for (let i = 0; i < a.length - 1; i++) {
      const num = a[i + 1] - a[i];
      if (num) b.push(num);
    }
    if (b.length < len) b.push(0);
    a = b.sort((a, b) => a - b);
  }
  return a[0];
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = Number(await read());
      const a = (await read()).split(' ').map(Number);
      res[i] = solve(n, a);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

let inputs,
    str = '';
function read() {
  return inputs.next().value.trim();
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});


Nash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the $$$n\times n$$$ board. Rows and columns of this board are numbered from $$$1$$$ to $$$n$$$. The cell on the intersection of the $$$r$$$-th row and $$$c$$$-th column is denoted by $$$(r, c)$$$.Some cells on the board are called blocked zones. On each cell of the board, there is written one of the following $$$5$$$ characters  — $$$U$$$, $$$D$$$, $$$L$$$, $$$R$$$ or $$$X$$$  — instructions for the player. Suppose that the current cell is $$$(r, c)$$$. If the character is $$$R$$$, the player should move to the right cell $$$(r, c+1)$$$, for $$$L$$$ the player should move to the left cell $$$(r, c-1)$$$, for $$$U$$$ the player should move to the top cell $$$(r-1, c)$$$, for $$$D$$$ the player should move to the bottom cell $$$(r+1, c)$$$. Finally, if the character in the cell is $$$X$$$, then this cell is the blocked zone. The player should remain in this cell (the game for him isn't very interesting from now on).It is guaranteed that the characters are written in a way that the player will never have to step outside of the board, no matter at which cell he starts.As a player starts from a cell, he moves according to the character in the current cell. The player keeps moving until he lands in a blocked zone. It is also possible that the player will keep moving infinitely long.For every of the $$$n^2$$$ cells of the board Alice, your friend, wants to know, how will the game go, if the player starts in this cell. For each starting cell of the board, she writes down the cell that the player stops at, or that the player never stops at all. She gives you the information she has written: for each cell $$$(r, c)$$$ she wrote:   a pair ($$$x$$$,$$$y$$$), meaning if a player had started at $$$(r, c)$$$, he would end up at cell ($$$x$$$,$$$y$$$).  or a pair ($$$-1$$$,$$$-1$$$), meaning if a player had started at $$$(r, c)$$$, he would keep moving infinitely long and would never enter the blocked zone. It might be possible that Alice is trying to fool you and there's no possible grid that satisfies all the constraints Alice gave you. For the given information Alice provided you, you are required to decipher a possible board, or to determine that such a board doesn't exist. If there exist several different boards that satisfy the provided information, you can find any of them.

The first line of the input contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^{3}$$$)  — the side of the board. The $$$i$$$-th of the next $$$n$$$ lines of the input contains $$$2n$$$ integers $$$x_1, y_1, x_2, y_2, \dots, x_n, y_n$$$, where $$$(x_j, y_j)$$$ ($$$1 \leq x_j \leq n, 1 \leq y_j \leq n$$$, or $$$(x_j,y_j)=(-1,-1)$$$) is the pair written by Alice for the cell $$$(i, j)$$$.

If there doesn't exist a board satisfying the information that Alice gave you, print a single line containing INVALID.  Otherwise, in the first line print VALID. In the $$$i$$$-th of the next $$$n$$$ lines, print the string of $$$n$$$ characters, corresponding to the characters in the $$$i$$$-th row of the suitable board you found. Each character of a string can either be $$$U$$$, $$$D$$$, $$$L$$$, $$$R$$$ or $$$X$$$. If there exist several different boards that satisfy the provided information, you can find any of them.

NoteFor the sample test 1 :The given grid in output is a valid one.   If the player starts at $$$(1,1)$$$, he doesn't move any further following $$$X$$$ and stops there.  If the player starts at $$$(1,2)$$$, he moves to left following $$$L$$$ and stops at $$$(1,1)$$$.  If the player starts at $$$(2,1)$$$, he moves to right following $$$R$$$ and stops at $$$(2,2)$$$.  If the player starts at $$$(2,2)$$$, he doesn't move any further following $$$X$$$ and stops there. The simulation can be seen below :   For the sample test 2 : The given grid in output is a valid one, as a player starting at any cell other than the one at center $$$(2,2)$$$, keeps moving in an infinitely long cycle and never stops. Had he started at $$$(2,2)$$$, he wouldn't have moved further following instruction $$$X$$$ .The simulation can be seen below :

function main(raw) {
    var lines = raw.trim().split("\n").map(function (v) { return v.trim().split(" ").map(function (u) { return parseInt(u, 10); }); });
    var n = lines.shift()[0];
    var matrix = lines.slice(0, n).map(function (line) { return line.reduce(function (a, v, i) {
        if (i % 2 == 0) {
            a[i / 2] = {
                y: v === -1 ? -1 : (v - 1),
                x: line[i + 1] === -1 ? -1 : (line[i + 1] - 1)
            };
        }
        return a;
    }, []); });
    var visited = matrix.map(function (v) { return v.map(function (u) { return false; }); });
    var result = matrix.map(function (v) { return v.map(function (u) { return null; }); });
    function dfsWhileValid(goal, src) {
        var queue = [src];
        var _loop_1 = function () {
            var _a = queue.shift(), x = _a.x, y = _a.y;
            var adj = [
                { x: x - 1, y: y },
                { x: x + 1, y: y },
                { x: x, y: y + 1 },
                { x: x, y: y - 1 }
            ].filter(function (v) { return 0 <= v.x && v.x < n
                && 0 <= v.y && v.y < n
                && matrix[v.y][v.x].x === goal.x
                && matrix[v.y][v.x].y === goal.y
                && !visited[v.y][v.x]; });
            adj.forEach(function (v) {
                result[v.y][v.x] = strDirection(v, { x: x, y: y });
                visited[v.y][v.x] = true;
                queue.push(v);
            });
        };
        while (queue.length > 0) {
            _loop_1();
        }
    }
    for (var y = 0; y < n; y++) {
        for (var x = 0; x < n; x++) {
            if (matrix[y][x].x === x && matrix[y][x].y === y) {
                dfsWhileValid({ x: x, y: y }, { x: x, y: y });
                result[y][x] = "X";
            }
        }
    }
    for (var y = 0; y < n; y++) {
        for (var x = 0; x < n; x++) {
            if (matrix[y][x].x === -1) {
                var adj = [
                    { x: x - 1, y: y },
                    { x: x + 1, y: y },
                    { x: x, y: y + 1 },
                    { x: x, y: y - 1 }
                ].filter(function (v) { return 0 <= v.x && v.x < n && 0 <= v.y && v.y < n; });
                var next = adj.find(function (u) { return matrix[u.y][u.x].x === -1; });
                if (next === undefined) {
                    console.log("INVALID");
                    return;
                }
                else {
                    result[y][x] = strDirection({ y: y, x: x }, next);
                }
            }
            else if (result[y][x] === null) {
                console.log("INVALID");
                return;
            }
        }
    }
    var str = "VALID\n";
    str += result.map(function (l) { return l.join(""); }).join("\n");
    console.log(str);
}
function strDirection(src, dst) {
    if (src.x < dst.x) {
        return "R";
    }
    else if (src.x > dst.x) {
        return "L";
    }
    else if (src.y > dst.y) {
        return "U";
    }
    else {
        return "D";
    }
}
(function () {
    var d = "";
    process.stdin.on("data", function (c) { return d += c; });
    process.stdin.on("end", function () { return main(d); });
})();

function main(raw) {
    var lines = raw.trim().split("\n").map(function (v) { return v.trim().split(" ").map(function (u) { return parseInt(u, 10); }); });
    var n = lines.shift()[0];
    var matrix = lines.slice(0, n).map(function (line) { return line.reduce(function (a, v, i) {
        if (i % 2 == 0) {
            a[i / 2] = {
                y: v === -1 ? -1 : (v - 1),
                x: line[i + 1] === -1 ? -1 : (line[i + 1] - 1)
            };
        }
        return a;
    }, []); });
    var result = matrix.map(function (v) { return v.map(function (u) { return null; }); });
    var hasher = function (p) { return p.x + "-" + p.y; };
    var visited = new Set();
    function dfsWhileValid(goal, _a) {
        var x = _a.x, y = _a.y;
        var adj = [
            { x: x - 1, y: y },
            { x: x + 1, y: y },
            { x: x, y: y + 1 },
            { x: x, y: y - 1 }
        ].filter(function (v) { return 0 <= v.x && v.x < n
            && 0 <= v.y && v.y < n
            && matrix[v.y][v.x].x === goal.x
            && matrix[v.y][v.x].y === goal.y
            && !visited.has(hasher(v)); });
        adj.forEach(function (v) {
            result[v.y][v.x] = strDirection(v, { x: x, y: y });
            visited.add(hasher(v));
            dfsWhileValid(goal, v);
        });
    }
    for (var y = 0; y < n; y++) {
        for (var x = 0; x < n; x++) {
            if (matrix[y][x].x === x && matrix[y][x].y === y) {
                dfsWhileValid({ x: x, y: y }, { x: x, y: y });
                result[y][x] = "X";
            }
        }
    }
    for (var y = 0; y < n; y++) {
        for (var x = 0; x < n; x++) {
            if (matrix[y][x].x === -1) {
                var adj = [
                    { x: x - 1, y: y },
                    { x: x + 1, y: y },
                    { x: x, y: y + 1 },
                    { x: x, y: y - 1 }
                ].filter(function (v) { return 0 <= v.x && v.x < n && 0 <= v.y && v.y < n; });
                var next = adj.find(function (u) { return matrix[u.y][u.x].x === -1; });
                if (next === undefined) {
                    console.log("INVALID");
                    return;
                }
                else {
                    result[y][x] = strDirection({ y: y, x: x }, next);
                }
            }
        }
    }
    console.log("VALID");
    result.forEach(function (l) { return console.log(l.join("")); });
}
function strDirection(src, dst) {
    if (src.x < dst.x) {
        return "R";
    }
    else if (src.x > dst.x) {
        return "L";
    }
    else if (src.y > dst.y) {
        return "U";
    }
    else {
        return "D";
    }
}
(function () {
    var d = "";
    process.stdin.on("data", function (c) { return d += c; });
    process.stdin.on("end", function () { return main(d); });
})();

function main(raw) {
    var lines = raw.trim().split("\n").map(function (v) { return v.trim().split(" ").map(function (u) { return parseInt(u, 10); }); });
    var n = lines.shift()[0];
    var matrix = lines.slice(0, n).map(function (line) { return line.reduce(function (a, v, i) {
        if (i % 2 == 0) {
            a[i / 2] = {
                x: v === -1 ? -1 : (v - 1),
                y: line[i + 1] === -1 ? -1 : (line[i + 1] - 1)
            };
        }
        return a;
    }, []); });
    var result = matrix.map(function (v) { return v.map(function (u) { return null; }); });
    var hasher = function (p) { return p.x + "-" + p.y; };
    var visited = new Set();
    function dfsWhileValid(goal, _a) {
        var x = _a.x, y = _a.y;
        var adj = [
            { x: x - 1, y: y },
            { x: x + 1, y: y },
            { x: x, y: y + 1 },
            { x: x, y: y - 1 }
        ].filter(function (v) { return 0 <= v.x && v.x < n
            && 0 <= v.y && v.y < n
            && matrix[v.y][v.x].x === goal.x
            && matrix[v.y][v.x].y === goal.y
            && !visited.has(hasher(v)); });
        adj.forEach(function (v) {
            result[v.y][v.x] = strDirection(v, { x: x, y: y });
            visited.add(hasher(v));
            dfsWhileValid(goal, v);
        });
    }
    for (var y = 0; y < n; y++) {
        for (var x = 0; x < n; x++) {
            if (matrix[y][x].x === x && matrix[y][x].y === y) {
                dfsWhileValid({ x: x, y: y }, { x: x, y: y });
                result[y][x] = "X";
            }
        }
    }
    for (var y = 0; y < n; y++) {
        for (var x = 0; x < n; x++) {
            if (matrix[y][x].x === -1) {
                var adj = [
                    { x: x - 1, y: y },
                    { x: x + 1, y: y },
                    { x: x, y: y + 1 },
                    { x: x, y: y - 1 }
                ].filter(function (v) { return 0 <= v.x && v.x < n && 0 <= v.y && v.y < n; });
                var next = adj.find(function (u) { return matrix[u.y][u.x].x === -1; });
                if (next === undefined) {
                    console.log("INVALID");
                    return;
                }
                else {
                    result[y][x] = strDirection({ y: y, x: x }, next);
                }
            }
        }
    }
    console.log("VALID");
    result.forEach(function (l) { return console.log(l.join("")); });
}
function strDirection(src, dst) {
    if (src.x < dst.x) {
        return "R";
    }
    else if (src.x > dst.x) {
        return "L";
    }
    else if (src.y > dst.y) {
        return "U";
    }
    else {
        return "D";
    }
}
(function () {
    var d = "";
    process.stdin.on("data", function (c) { return d += c; });
    process.stdin.on("end", function () { return main(d); });
})();

function main(raw) {
    var lines = raw.trim().split("\n").map(function (v) { return v.trim().split(" ").map(function (u) { return parseInt(u, 10); }); });
    var n = lines.shift()[0];
    var matrix = lines.slice(0, n).map(function (line) { return line.reduce(function (a, v, i) {
        if (i % 2 == 0) {
            a[i / 2] = { x: v === -1 ? -1 : (v - 1), y: line[i + 1] === -1 ? -1 : (line[i + 1] - 1) };
        }
        return a;
    }, []); });
    var result = matrix.map(function (v) { return v.map(function (u) { return null; }); });
    var hasher = function (p) { return p.x + "-" + p.y; };
    var visited = new Set();
    function dfsWhileValid(goal, _a) {
        var x = _a.x, y = _a.y;
        if (visited.has(hasher({ x: x, y: y }))) {
            return;
        }
        [
            { x: x - 1, y: y },
            { x: x + 1, y: y },
            { x: x, y: y + 1 },
            { x: x, y: y - 1 }
        ].filter(function (v) { return 0 <= v.x && v.x < n
            && 0 <= v.y && v.y < n
            && matrix[v.y][v.x].x === goal.x
            && matrix[v.y][v.x].y === goal.y; }).forEach(function (v) {
            result[v.y][v.x] = strDirection(v, { x: x, y: y });
            visited.add(hasher(v));
            dfsWhileValid(goal, v);
        });
    }
    for (var y = 0; y < n; y++) {
        for (var x = 0; x < n; x++) {
            if (matrix[y][x].x === x && matrix[y][x].y === y) {
                result[y][x] = "X";
                dfsWhileValid({ x: x, y: y }, { x: x, y: y });
            }
        }
    }
    for (var y = 0; y < n; y++) {
        for (var x = 0; x < n; x++) {
            if (matrix[y][x].x === -1) {
                var adj = [
                    { x: x - 1, y: y },
                    { x: x + 1, y: y },
                    { x: x, y: y + 1 },
                    { x: x, y: y - 1 }
                ].filter(function (v) { return 0 <= v.x && v.x < n && 0 <= v.y && v.y < n; });
                var next = adj.find(function (u) { return matrix[u.y][u.x].x === -1; });
                if (next === undefined) {
                    console.log("INVALID");
                    return;
                }
                else {
                    result[y][x] = strDirection({ y: y, x: x }, next);
                }
            }
        }
    }
    console.log("VALID");
    result.forEach(function (l) { return console.log(l.join("")); });
}
function strDirection(src, dst) {
    if (src.x < dst.x) {
        return "R";
    }
    else if (src.x > dst.x) {
        return "L";
    }
    else if (src.y > dst.y) {
        return "U";
    }
    else {
        return "D";
    }
}
(function () {
    var d = "";
    process.stdin.on("data", function (c) { return d += c; });
    process.stdin.on("end", function () { return main(d); });
})();

function main(raw) {
    var lines = raw.trim().split("\n").map(function (v) { return v.trim().split(" ").map(function (u) { return parseInt(u, 10); }); });
    var n = lines.shift()[0];
    var matrix = lines.slice(0, n).map(function (line) { return line.reduce(function (a, v, i) {
        if (i % 2 == 0) {
            a[i / 2] = { x: v - 1, y: line[i + 1] - 1 };
        }
        return a;
    }, []); });
    var result = matrix.map(function (v) { return v.map(function (u) { return null; }); });
    var hasher = function (p) { return p.x + "-" + p.y; };
    var visited = new Set();
    function dfsWhileValid(goal, _a) {
        var x = _a.x, y = _a.y;
        if (visited.has(hasher({ x: x, y: y }))) {
            return;
        }
        [
            { x: x - 1, y: y },
            { x: x + 1, y: y },
            { x: x, y: y + 1 },
            { x: x, y: y - 1 }
        ].filter(function (v) { return 0 <= v.x && v.x < n
            && 0 <= v.y && v.y < n
            && matrix[v.y][v.x].x === goal.x
            && matrix[v.y][v.x].y === goal.y; }).forEach(function (v) {
            result[v.y][v.x] = strDirection(v, { x: x, y: y });
            visited.add(hasher(v));
            dfsWhileValid(goal, v);
        });
    }
    for (var y = 0; y < n; y++) {
        for (var x = 0; x < n; x++) {
            if (matrix[y][x].x === x && matrix[y][x].y === y) {
                result[y][x] = "X";
                dfsWhileValid({ x: x, y: y }, { x: x, y: y });
            }
        }
    }
    for (var y = 0; y < n; y++) {
        for (var x = 0; x < n; x++) {
            if (matrix[y][x].x === -1) {
                var adj = [
                    { x: x - 1, y: y },
                    { x: x + 1, y: y },
                    { x: x, y: y + 1 },
                    { x: x, y: y - 1 }
                ].filter(function (v) { return 0 <= v.x && v.x < n && 0 <= v.y && v.y < n; });
                var next = adj.find(function (u) { return matrix[u.y][u.x].x === -1; });
                if (next === undefined) {
                    console.log("INVALID");
                    return;
                }
                else {
                    result[y][x] = strDirection({ y: y, x: x }, next);
                }
            }
        }
    }
    console.log("VALID");
    result.forEach(function (l) { return console.log(l.join(" ")); });
}
function strDirection(src, dst) {
    if (src.x < dst.x) {
        return "R";
    }
    else if (src.x > dst.x) {
        return "L";
    }
    else if (src.y > dst.y) {
        return "U";
    }
    else {
        return "D";
    }
}
(function () {
    var d = "";
    process.stdin.on("data", function (c) { return d += c; });
    process.stdin.on("end", function () { return main(d); });
})();


Polycarp bought a new expensive painting and decided to show it to his $$$n$$$ friends. He hung it in his room. $$$n$$$ of his friends entered and exited there one by one. At one moment there was no more than one person in the room. In other words, the first friend entered and left first, then the second, and so on.It is known that at the beginning (before visiting friends) a picture hung in the room. At the end (after the $$$n$$$-th friend) it turned out that it disappeared. At what exact moment it disappeared — there is no information.Polycarp asked his friends one by one. He asked each one if there was a picture when he entered the room. Each friend answered one of three:  no (response encoded with 0);  yes (response encoded as 1);  can't remember (response is encoded with ?). Everyone except the thief either doesn't remember or told the truth. The thief can say anything (any of the three options).Polycarp cannot understand who the thief is. He asks you to find out the number of those who can be considered a thief according to the answers.

The first number $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The following is a description of test cases. The first line of each test case contains one string $$$s$$$ (length does not exceed $$$2 \cdot 10^5$$$) — a description of the friends' answers, where $$$s_i$$$ indicates the answer of the $$$i$$$-th friend. Each character in the string is either 0 or 1 or ?. The given regularity is described in the actual situation. In particular, on the basis of answers, at least one friend can be suspected of stealing a painting. It is guaranteed that the sum of string lengths over the entire input data set does not exceed $$$2 \cdot 10^5$$$.

Output one positive (strictly more zero) number – the number of people who could steal the picture based on the data shown.

NoteIn the first case, the answer is $$$1$$$ since we had exactly $$$1$$$ friend.The second case is similar to the first.In the third case, the suspects are the third and fourth friends (we count from one). It can be shown that no one else could be the thief.In the fourth case, we know absolutely nothing, so we suspect everyone.

'use strict';

var readline = require('readline');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(s) {
  if (s.length === 1) {
    console.log(1);
    return;
  }
  const n = s.length;
  let l = 0,
      r = n - 1;
  for (let i = 0; i < n; i++) {
    if (s[i] === '1') {
      l = i;
    }
  }
  for (let i = n - 1; i >= 0; i--) {
    if (s[i] === '0') {
      r = i;
    }
  }
  if (r < l) {
    console.log(1);
    return;
  }
  console.log(r - l + 1);
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    const s = await read();
    solve(s);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

const rdline = require('readline');
const rl = rdline.createInterface({
    input: process.stdin
});

let lines = [];
rl.on('line', (line) => {
    lines.push(line);
}).on('close', () => {
    // input in lines
    solve();
});

let line = 0;
const readline = () => lines[line++];
solve = () => {
    const t = parseInt(readline());
    for (let i = 0; i < t; i++) {
        const s = readline();
        const l = s.lastIndexOf('1');
        const f = s.indexOf('0');
        var n = s.length;
        if (n === 1) {
            console.log(1);
        } else  if (s[0] === '0') {
            console.log(1);
        } else
        if (s[n - 1] === '1') {
            console.log(1);
        } else
        if (l === -1 && f === -1) {
            console.log(n);
        } else
        if (l === -1) {
            console.log(f + 1);
        } else
        if (f === -1) {
            console.log(n - l);
        } else {
          console.log(f - l + 1);
        }

    }
}

const solve = (str)=>{
     let yes = 0;
     for(let i=0;i<str.length;i++){
          if(str[i]==="1") yes = i;
          else if(str[i]==="0"){
               return i - yes + 1;
          }
     }
     return yes===0 ? str.length : str.length - yes;
}
function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for (let i = 0; i < t; i++) {
       console.log(solve(readline().trim()));
  }
}
main();

let readline = require("readline");
let rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false,
});

let lines = 0;
rl.on("line", function (line) {
  if (lines !== 0) {
    let input = line.split("");
    if (input.length === 1) {
      return console.log(1);
    }
    if (input[input.length - 1] === "1") {
      return console.log(1);
    }
    if (input[0] === "0") {
      return console.log(1);
    }
    const indexOf0 = input.indexOf("0");
    const indexOf1 = input.lastIndexOf("1");

    if (indexOf0 === -1 && indexOf1 === -1) {
      return console.log(input.length);
    }
    if (indexOf1 === -1) {
      return console.log(indexOf0 + 1);
    }
    if (indexOf0 === -1) {
      return console.log(input.length - indexOf1);
    }
    console.log(indexOf0 - indexOf1 + 1);
  }
  lines++;
});

const lines = [];
const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
rl.on('line', line => lines.push(line));
rl.on('close', main);
let rli = 0;
function readline() {
    return lines[rli++];
}

const ra = ()=>readline().split(' ').map(a=>+a);

function div(val, by){
    return (val - val % by) / by;
}

const cnk = (n, k) => {
    let res = 1;
    for (let i = 1; i <= k; i++)
        res = res * (n - k + i) / i;
    return Math.round(res + 0.01);
}

const sumab = (a, b) => {
    let x = (b - a + 1);
    let y = a + b;
    if (x % 2 === 0) {
        x = Math.round(x / 2);
    } else {
        y = Math.round(y / 2);
    }
    return BigInt(x) * BigInt(y);
}

const calc = (a)=>{
    let n = a.length;
    if (n === 1) return 1;

    let result = 1;
    let pos1 = 0;
    let pos0 = n - 1;

    for (let i = 0; i < n; i++) {
        if (a[i] === '0') {
            pos0 = i;
            break;
        }
    }

    for (let i = n - 1; i >= 0; i--) {
        if (a[i] === '1') {
            pos1 = i;
            break;
        }
    }

    if (pos0 < pos1) return n;
    return pos0 - pos1 + 1;
};

function main() {
    let T = +readline();
    for (let t = 1; t <= T; t++){
        // let n = +readline();
        // let a = ra();
        let a = readline().split('');
        console.log(`${calc(a)}`);
    }
}

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const str = lines[l++]
        output[i] = solve(str)
    }
    console.log(output.join('\n'))
// })()
})

function solve(str) {
    // no 1 after, no 0 before
    const one = []
    const zero = []
    for (let i = 0; i < str.length; i++) {
        let now = 0
        if (str[i] === '0') now = 1
        zero[i] = i ? zero[i - 1] + now : now
    }
    for (let i = str.length - 1; i >= 0; i--) {
        let now = 0
        if (str[i] === '1') now = 1
        one[i] = i < str.length - 1 ? one[i + 1] + now : now
    }
    let ans = 0
    for (let i = 0; i < str.length; i++) {
        if (!zero[i - 1] && !one[i + 1]) ans++
    }
    return ans
}

'use strict';
// HEADER:
const print = console.log;
let IS_MULTITEST, testN;
const pcalc = testN=>{
  let res = calc(testN);
  if (Array.isArray(res)){
    pa(res);
  } else if (Number.isFinite(res) || typeof res=='string'){
    print(res);
  }
};

const main = ()=>{
  if (IS_MULTITEST){
    let T = +readline()
    for (testN=1; testN<=T; testN++)
      pcalc(T);
  } else
   pcalc();
};

const lines = [];
const rl = require('readline').createInterface({
   input: process.stdin, output: process.stdout});
rl.on('line', line=>{
  lines.push(line);
});
rl.on('close', main);
let rli = 0;
const readline = ()=>lines[rli++];
const L = process.env.DEBUG ? console.log : ()=>{};
const LT = obj=>L(`Test #${testN}`, obj);

const ra = ()=>readline().split(' ').map(a=>+a)
const pa = arr=>print(arr.join(' '));

// SOLUTION:
IS_MULTITEST = 1;

const calc = ()=>{
  // READING:
  let s = readline();
  let n = s.length;
  LT({n, s});
  // PROCESSING:
  let ones = [];
  let zeros = [];
  for (let i=0; i<n; i++){
    if (s[i]=='1'){
      ones.push(i);
    }
    if (s[i]=='0'){
      zeros.push(i);
    }
  }
  let from = ones.length>=1 ? ones[ones.length-1] : 0;
  let to = zeros.length>=1 ? zeros[0] : n-1;
  return to-from+1;
};

'use strict';

var readline = require('readline');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(s) {
  if (s.length === 1) {
    console.log(1);
    return;
  }
  const n = s.length;
  let cache = new Map();
  const check = i => {
    if (cache.has(i)) return cache.get(i);
    if (i < 0) {
      cache.set(i, true);
    } else if (s[i] === '1') {
      cache.set(i, check(i - 1));
    } else if (s[i] === '?') {
      cache.set(i, check(i - 1));
    } else {
      cache.set(i, false);
    }
    return cache.get(i);
  };
  let res = new Set();
  for (let i = n - 1; i >= 0; i--) {
    if (check(i - 1)) res.add(i);
    if (s[i] === '1') break;
  }
  console.log(res.size);
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    const s = await read();
    solve(s);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict';

var readline = require('readline');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(s) {
  if (s.length === 1) {
    console.log(1);
    return;
  }
  const n = s.length;
  let cache = new Map();
  const check = i => {
    if (cache.has(i)) return cache.get(i);
    if (i < 0) {
      cache.set(i, true);
    } else if (s[i] === '1') {
      cache.set(i, true);
    } else if (s[i] === '?') {
      cache.set(i, check(i - 1));
    } else {
      cache.set(i, false);
    }
    return cache.get(i);
  };
  let res = new Set();
  for (let i = n - 1; i >= 0; i--) {
    if (check(i - 1)) res.add(i);
    if (s[i] === '1') break;
  }
  console.log(res.size);
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    const s = await read();
    solve(s);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict';

var readline = require('readline');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(s) {
  console.log(s);
  if (s.length === 1) {
    console.log(1);
    return;
  }
  const n = s.length;
  let cache = new Map();
  const check = i => {
    if (cache.has(i)) return cache.get(i);
    if (i < 0) {
      cache.set(i, true);
    } else if (s[i] === '1') {
      cache.set(i, true);
    } else if (s[i] === '?') {
      cache.set(i, check(i - 1));
    } else {
      cache.set(i, false);
    }
    return cache.get(i);
  };
  let res = new Set();
  for (let i = n - 1; i >= 0; i--) {
    if (check(i - 1)) {
      res.add(i);
    }
    if (s[i] === '1') {
      break;
    }
  }
  console.log(res.size);
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    const s = await read();
    solve(s);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();