var stdin_input = "";
var stdin_input_itr;
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { stdin_input_itr = stdin_input.split('\n').values(); main(); });

const rl = () => stdin_input_itr.next().value;
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

function main () {
	let T = rn();
	while (T--) {
		const [n, m] = rna();

		const used = [];
		for (let i = 0; i < m; i++) {
			const [a, b, c] = rna();
			used[b] = 1;
		}

		let root;
		for (let i = 1; i <= n; i++) if (!used[i]) root = i;

		for (let i = 1; i <= n; i++) if (i != root) console.log(i, root);
	}
}

"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, k] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let node = [];
    for (let i = 0; i < k; i++) {
      node.push(
        readline()
          .trim()
          .split(" ")
          .map((cur) => parseInt(cur))
      );
    }
    let res,
      obj = {};
    for (let i = 0; i < k; i++) obj[node[i][1]] = 1;
    for (let i = 1; i <= n; i++) {
      if (!obj[i]) {
        res = i;
        break;
      }
    }
    for (let i = 1; i <= n; i++) {
      if (i !== res) {
        console.log(`${res} ${i}`);
      }
    }
  }
};
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, k] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let node = [];
    for (let i = 0; i < k; i++) {
      node.push(
        readline()
          .trim()
          .split(" ")
          .map((cur) => parseInt(cur))
      );
    }
    let res = [],
      obj = {};
    const push = (n1, n2) => {
      if (!obj[n1]) {
        res.push(n1);
        obj[n1] = 1;
      }
      if (!obj[n2]) {
        res.push(n2);
        obj[n2] = 1;
      }
    };
    for (let i = 0; i < k; i++) {
      push(node[i][0], node[i][2]);
    }
    for (let i = 0; i < k; i++) {
      if (!obj[node[i][1]]) res.push(node[i][1]);
    }
    for (let i = 0; i < n - 1; i++) {
      console.log(res[i] + " " + res[i + 1]);
    }
  }
};
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, k] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let node = [];
    for (let i = 0; i < k; i++) {
      node.push(
        readline()
          .trim()
          .split(" ")
          .map((cur) => parseInt(cur))
      );
    }
    let res = [],
      obj = {},
      start = node[0][0];
    obj[node[0][0]] = 1;
    obj[node[0][2]] = 1;
    res.push([node[0][0], node[0][2]]);
    for (let i = 1; i < k; i++) {
      if (!obj[node[i][0]] || !obj[node[i][2]]) {
        res.push([node[i][0], node[i][2]]);
        if (!obj[node[i][0]] && !obj[node[i][2]]) {
          res.push([node[i][0], node[i - 1][2]]);
        }
        obj[node[i][0]] = 1;
        obj[node[i][2]] = 1;
      }
    }
    for (let i = 0; i < k; i++) {
      if (!obj[node[i][1]]) {
        res.push([start, node[i][1]]);
        obj[node[i][1]] = 1;
      }
    }
    for (let i = 0; i < res.length; i++) {
      console.log(res[i].join(" "));
    }
  }
};
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, k] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let node = [];
    for (let i = 0; i < k; i++) {
      node.push(
        readline()
          .trim()
          .split(" ")
          .map((cur) => parseInt(cur))
      );
    }
    let res = [],
      obj = {},
      start = node[0][0];
    obj[node[0][0]] = 1;
    obj[node[0][2]] = 1;
    res.push([node[0][0], node[0][2]]);
    for (let i = 1; i < k; i++) {
      if (!obj[node[i][0]] || !obj[node[i][2]]) {
        res.push([node[i][0], node[i][2]]);
        if (!obj[node[i][0]] && !obj[node[i][2]]) {
          if (!obj[node[i][0]]) res.push([node[i][0], node[i - 1][0]]);
          else res.push([node[i][2], node[i - 1][2]]);
        }
        obj[node[i][0]] = 1;
        obj[node[i][2]] = 1;
      }
    }
    for (let i = 0; i < k; i++) {
      if (!obj[node[i][1]]) {
        res.push([start, node[i][1]]);
        obj[node[i][1]] = 1;
      }
    }
    for (let i = 0; i < res.length; i++) {
      console.log(res[i].join(" "));
    }
  }
};
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, k] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let node = [];
    for (let i = 0; i < k; i++) {
      node.push(
        readline()
          .trim()
          .split(" ")
          .map((cur) => parseInt(cur))
      );
    }
    let res = [],
      obj = {},
      start = node[0][0];
    for (let i = 0; i < k; i++) {
      if (!obj[node[i][0]] || !obj[node[i][2]]) {
        res.push([node[i][0], node[i][2]]);
        obj[node[i][0]] = 1;
        obj[node[i][2]] = 1;
      }
    }
    for (let i = 0; i < k; i++) {
      if (!obj[node[i][1]]) {
        res.push([start, node[i][1]]);
        obj[node[i][1]] = 1;
      }
    }
    for (let i = 0; i < res.length; i++) {
      console.log(res[i].join(" "));
    }
  }
};
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, k] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let node = [];
    for (let i = 0; i < k; i++) {
      node.push(
        readline()
          .trim()
          .split(" ")
          .map((cur) => parseInt(cur))
      );
    }
    let res = [],
      obj = {};
    for (let i = 0; i < k; i++) {
      if (!obj[node[i][2]] || !obj[node[i][0]]) {
        if (!obj[node[i][0]]) res.push([node[i][2], node[i][0]]);
        else res.push([node[i][0], node[i][2]]);
        obj[node[i][2]] = 1;
        obj[node[i][0]] = 1;
      }
      if (!obj[node[i][0]] || !obj[node[i][1]]) {
        if (!obj[node[i][1]]) res.push([node[i][0], node[i][1]]);
        else res.push([node[i][1], node[i][0]]);
        obj[node[i][1]] = 1;
        obj[node[i][0]] = 1;
      }
    }
    for (let i = 0; i < res.length; i++) {
      console.log(res[i].join(" "));
    }
  }
};
solve();

var stdin_input = "";
var stdin_input_itr;
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { stdin_input_itr = stdin_input.split('\n').values(); main(); });

const rl = () => stdin_input_itr.next().value;
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

function main () {
	let T = rn();
	while (T--) {
		const [n, m] = rna();

		const used = [];
		for (let i = 0; i < m; i++) {
			let [a, b, c] = rna();
			if (a > c) [a, c] = [c, a];
			console.log(a, c);
			used[a] = 1;
		}

		for (let i = 1, u; i <= n; i++) {
			if (!used[i]) {
				if (u) console.log(u, i);
				u = i;
			}
		}
	}
}

var stdin_input = "";
var stdin_input_itr;
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { stdin_input_itr = stdin_input.split('\n').values(); main(); });

const rl = () => stdin_input_itr.next().value;
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

function main () {
	let T = rn();
	while (T--) {
		const [n, m] = rna();

		const used = [];
		for (let i = 0; i < m; i++) {
			let [a, b, c] = rna();
			if (a > b) [a, b] = [b, a];
			console.log(a, c);
			used[c] = 1;
		}

		for (let i = 0, u; i < n; i++) {
			if (!used[i]) {
				if (u) console.log(u+1, i+1);
				u = i;
			}
		}
	}
}


//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = []; var outputList = [];var retcode = new Set();
read.on('line', function(input){
	var tmp = input.split(' ');
	for(var i = 0; i < tmp.length; i++){
		inLine.push(tmp[i]);
		if(i == tmp.length - 1){
			retcode.add(inLine.length);
		}
	}
});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
	console.log(myconv(outputList, 9));
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextArray(size, code){
	var ret = new Array(size);
	for(var i = 0; i < size; i++){
		if(code == 'int'){
			ret[i] = nextInt();
		}else if(code == 'long'){
			ret[i] = nextLong();
		}else if(code == 'double'){
			ret[i] = nextDouble();
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}
function getCountMap(list){
	var map = {};
	for(var i = 0; i < list.length; i++){
		if(map[list[i]] == null){
			map[list[i]] = 0;
		}
		map[list[i]]++;
	}
	return map;
}
function init(input){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},
		isReturn : function(){return retcode.has(this.index);}
	};
}
function myout(s){outputList.push(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
function isReturn(){return obj.isReturn();}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var S = next();
		var x = nextInt();
		var tmp = S;
		var output = 0;
		while(true){
			var L = myconv(tmp.split(":")[0], 1);
			var R = myconv(tmp.split(":")[1], 1);
			var V = L * 60 + R;
			V += x;
			var LS = Math.floor(V / 60);
			if(LS >= 24){
				LS %= 24;
			}
			if(LS < 10){
				LS = "0" + LS;
			}
			var RS = V % 60;
			if(RS < 10){
				RS = "0" + RS;
			}
			tmp = LS + ":" + RS;
			var ok = true;
			for(var i = 0; i < tmp.length; i++){
				if(tmp[i] != tmp[tmp.length - 1 - i]){
					ok = false;
				}
			}
			if(ok){
				output++;
			}
			if(tmp == S){
				break;
			}
		}
		myout(output);
	}
}

// https://codeforces.com/blog/entry/69610

'use strict';

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 print(v) {
    console.log(v);
}
const palindromes = [
    "00:00",
    "01:10",
    "02:20",
    "03:30",
    "04:40",
    "05:50",
    "10:01",
    "11:11",
    "12:21",
    "13:31",
    "14:41",
    "15:51",
    "20:02",
    "21:12",
    "22:22",
    "23:32",
];

const timeToMm = (v) => {
    const [hh, mm] = v.split(":").map(t => parseInt(t));
    return hh * 60 + mm;
};

const palindromeMinutes = palindromes.map(timeToMm);

// taken from https://codeforces.com/contest/1692/submission/170087380
const solve = () => {
    const [time, incrementStr] = readline().split(" ");
    const startTimeMm = timeToMm(time);
    const increment = parseInt(incrementStr);
    let answer = 0;
    let running = startTimeMm;
    const s = new Set();
    const pad = (v) => ("0" + v).substr(-2);
    const isPalindrome = (a) => a === a.split("").reverse().join("");
    while (true) {
        const timeToCheck = pad(Math.floor(running / 60)) + ":" + pad(running % 60);
        if (s.has(timeToCheck))
            break;

        if (isPalindrome(timeToCheck))
            answer++;

        s.add(timeToCheck);

        running += increment;
        running %= 1440;
    }
    print(answer);
}

/*
const gcd = (a, b) => {
    if (b == 0) {
        return a;
    }
    return gcd(b, a % b);
};

const lcm = (a, b) => a * b / gcd(a, b);

const solve = () => {
    const [time, incrementStr] = readline().split(" ");
    print(`time ${time}`);
    print(`incrementStr ${incrementStr}`);
    const startTimeMm = timeToMm(time);
    const increment = parseInt(incrementStr);
    print(`startTimeMm ${startTimeMm}`);
    let counter = 0;
    for (const palindromeTime of palindromeMinutes) {
        if ((lcm(palindromeTime, startTimeMm) - startTimeMm) % increment == 0)
            counter++;
    }
    print(counter);
};
*/

const main = () => {
    const t = parseInt(readline());
    for (let i = 0; i < t; i++) {
        solve();
    }
};

function solve() {
  const [a, b] = cl().split(' ');
  const bN = Number(b);
  const n = 60 * 24 / bN;
  let start = strToM(a);
  let count = 0;
  const set = new Set();
  while (!set.has(start)) {
    if (MIs(start)) {
      count += 1;
    }
    set.add(start);
    start += bN;
    start %= 1440;
  }
  co(count);
}

function strToM(str) {
  const [a, b] = str.split(':').map((item) => Number(item));
  return a * 60 + b;
}

function MIs(m) {
  m = m % 1440;
  const b = m % 60;
  const a = m / 60 | 0;
  const bStr = b < 10 ? '0' + b : '' + b;
  const aStr = a < 10 ? '0' + a : '' + a;
  return aStr[0] === bStr[1] && aStr[1] === bStr[0];
}

function Solution() {
  let n = Number(cl());
  while (n--) {
    solve();
  }
}

function cl() {
  return lines.shift();
}

function co(str) {
  console.log(str);
}

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', Solution);

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 [time, p] = lines[l++].trim().split(' ')
        output[i] = solve(time, p)
    }
    console.log(output.join('\n'))
// })()
})

function solve(time, p) {
    p = +p
    const [h, m] = time.split(':').map(Number)
    const now = h * 60 + m
    let d = 0
    let ans = 0
    const map = {}
    while (1) {
        const k = cal(now + d)
        if (map[k]) break
        map[k] = 1
        if (isp(k)) ans++
        d += p
        // if (d > 2440) break
    }
    return ans
}
function cal(now) {
    let h = Math.floor(now / 60)
    h %= 24
    if (h < 10) h = '0' + h
    let m = now % 60
    if (m < 10) m = '0' + m
    const s = h + ':' + m
// console.log(s)
    return s
}
function isp(s) {
    for (let i = 0; i < s.length; i++) {
        if (s[i] !== s[s.length - 1 - i]) return false
    }
    return true
}

'use strict';

function solve(a) {
  const [h, m] = a[0].split(':').map(Number),
        t = Number(a[1]);
  let h1 = h,
      m1 = m;
  const set = new Set();
  const check = () => {
    const a = h1.toString().padStart(2, '0'),
          b = m1.toString().padStart(2, '0');
    const str = `${a}${b}`;
    if (str === str.split('').reverse().join('')) set.add(str);
  };
  const next = () => {
    m1 += t;
    h1 += Math.floor(m1 / 60);
    h1 %= 24;
    m1 %= 60;
  };
  check();
  next();
  while (h1 !== h || m1 !== m) {
    check();
    next();
  }
  return set.size;
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const a = (await read()).split(' ');
      res[i] = solve(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);
});

/**
 * Author : Fazlul Hoque
 * Node.js version : 12.16.3
 * command : node fileName.js <input.txt >output.txt
 */
"use strict";
process.stdin.resume();
process.stdin.setEncoding("utf-8");
let inputString = ""; //An array of  raw inputs (includes 'n,\r , not usable. need to process before use)
let currentLine = 0; //input sequence controller variable.

process.stdin.on("data", (inputStdin) => {
    inputString += inputStdin;
});
process.stdin.on("end", () => {
    inputString = inputString.split("\n");
    main(); // after input
});

/********** Utility Functions Start **********/
/**
 *  read row Input
 * @returns string
 */
function _readRawLine() {
    return inputString[currentLine++];
}
function readLine() {
    // return _readRawLine().replace(/\s+$/g, '');
    return _readRawLine().replace("\r", "");
}

function print(x) {
    console.log(x);
}

function readSingleInt() {
    const p = readLine();
    return parseInt(p);
}

function readIntArray() {
    return readLine()
        .split(" ")
        .map((v) => parseInt(v));
}

function readArray() {
    return readLine().split(" ");
}

function int(n) {
    return parseInt(n);
}
/********** Utility Functions End **********/
/**
 * Don't Touch this fucntion at all , unless you know what are you doing!
 */
function main() {
    solve();
}

// ********** actual Code Starts from here **********
function revStr(str){
    return Array.from(str).reverse().join('');
}
function palindromeTimeList(){
    const timesAr = [];
    for(let i=0;i<16;i++){
        let tm = i;
        if(tm<10){
            tm = `0${tm}`;
        }
        else{
            tm = `${tm}`
        }
        let acTime = `${tm}:${revStr(tm)}`;
        let cvMin = tm*60 + parseInt(revStr(tm)) ;
        // console.log(acTime , cvMin)

        timesAr.push(cvMin);
    }
    return timesAr;
}
function isPalindromeTime(timeStr = '')
{
    const revStr = timeStr.split('').reverse().join('');
    return (revStr==timeStr );
}
function convertTime(n){
    let hour = Math.floor(n/60)%24;
    n = n%60;
    if(hour<10){
        hour = `0${hour}`;
    }
    if(n<10){
        n = `0${n}`;
    }
    return `${hour}:${n}`;
}
function solve() {
   let t= readSingleInt();
   const arTime = palindromeTimeList();
   while(t--)
   {
       let [timeString,interval]=  readLine().split(' ');
       interval = parseInt(interval);
       let [hour ,min] = timeString.split(':').map( v=> parseInt(v));
       let time = hour*60 + min;
        let ans =0;
        if(isPalindromeTime(timeString)){
            ans++;
        }
       for(let i=time+interval;;i+=interval){
            // console.log('hi')
            const cvs = convertTime(i) ;
            if(cvs==timeString){
                break;
            }
            let res =  isPalindromeTime( convertTime(i) );
            // console.log(cvs)
            if(res){
                ans++;
                // console.log(cvs)
            }
       }

    //    palindromeTimeList()
    //    console.log(isPalindromeTime('07:57'))
       console.log(ans)

   }
}

/*
** 799D
*/

// Common Template Starts //
//*
process.stdin.resume();
process.stdin.setEncoding("utf-8");

let is = "";
let cl = 0;

process.stdin.on("data", (inp) => {
    is += inp;
});

process.stdin.on("end", (_) => {
    is = is.trim().split("\n").map((s) => s.trim());
    main();
});

const readline = () => is[cl++];

// Common Template Ends //

const isPalindrome = (n) => {
  const m = n % 60;
  const h = (n - m) / 60;
  const h1 = h % 10;
  const h0 = (h - h1) / 10;
  return `${h1}${h0}` === `${m < 10 ? '0' : ''}${m}`;
}

const toTime = (hhmm) => {
  const [h, m] = hhmm.split(':').map(n => parseInt(n));
  return h * 60 + m;
}

function main() {
  let nLines = parseInt(readline());
  while(nLines--) {
    const [time, x] = readline().split(' ');
    const start = toTime(time);
    const min = parseInt(x);
    let current = (start + min) % 1440;
    let n = isPalindrome(start) ? 1 : 0;
    while (current !== start) {
      if (isPalindrome(current)) n++;
      current = (current + min) % 1440;
    }

    console.log(n);
  }
}

/**
 * Author : Fazlul Hoque
 * Node.js version : 12.16.3
 * command : node fileName.js <input.txt >output.txt
 */
"use strict";
process.stdin.resume();
process.stdin.setEncoding("utf-8");
let inputString = ""; //An array of  raw inputs (includes 'n,\r , not usable. need to process before use)
let currentLine = 0; //input sequence controller variable.

process.stdin.on("data", (inputStdin) => {
    inputString += inputStdin;
});
process.stdin.on("end", () => {
    inputString = inputString.split("\n");
    main(); // after input
});

/********** Utility Functions Start **********/
/**
 *  read row Input
 * @returns string
 */
function _readRawLine() {
    return inputString[currentLine++];
}
function readLine() {
    // return _readRawLine().replace(/\s+$/g, '');
    return _readRawLine().replace("\r", "");
}

function print(x) {
    console.log(x);
}

function readSingleInt() {
    const p = readLine();
    return parseInt(p);
}

function readIntArray() {
    return readLine()
        .split(" ")
        .map((v) => parseInt(v));
}

function readArray() {
    return readLine().split(" ");
}

function int(n) {
    return parseInt(n);
}
/********** Utility Functions End **********/
/**
 * Don't Touch this fucntion at all , unless you know what are you doing!
 */
function main() {
    solve();
}

// ********** actual Code Starts from here **********

function isPalindromeTime(timeStr = '')
{
    const revStr = timeStr.split('').reverse().join('');
    return (revStr==timeStr );
}
function convertTime(n){
    let hour = Math.floor(n/60)%24;
    n = n%60;
    if(hour<10){
        hour = `0${hour}`;
    }
    if(n<10){
        n = `0${n}`;
    }
    return `${hour}:${n}`;
}
function solve() {
   let t= readSingleInt();
   while(t--)
   {
       let [timeString,interval]=  readLine().split(' ');
       interval = parseInt(interval);
       let [hour ,min] = timeString.split(':').map( v=> parseInt(v));
       let time = hour*60 + min;
        let ans =0;
        let list = new Set();
        if(isPalindromeTime(timeString)){
            ans++;
            list.add(timeString);
        }
       for(let i=time+interval;i<95*24*60;i+=interval){
            // console.log('hi')
            const cvs = convertTime(i) ;
            // if(cvs==timeString){
            //     break;
            // }
            let res =  isPalindromeTime( convertTime(i) );
            // console.log(cvs)
            if(res){
                ans++;
                list.add(cvs);
                // console.log(cvs)
            }
       }

    //    palindromeTimeList()
    //    console.log(isPalindromeTime('07:57'))
       console.log(list.size)

   }
}

/**
 * Author : Fazlul Hoque
 * Node.js version : 12.16.3
 * command : node fileName.js <input.txt >output.txt
 */
"use strict";
process.stdin.resume();
process.stdin.setEncoding("utf-8");
let inputString = ""; //An array of  raw inputs (includes 'n,\r , not usable. need to process before use)
let currentLine = 0; //input sequence controller variable.

process.stdin.on("data", (inputStdin) => {
    inputString += inputStdin;
});
process.stdin.on("end", () => {
    inputString = inputString.split("\n");
    main(); // after input
});

/********** Utility Functions Start **********/
/**
 *  read row Input
 * @returns string
 */
function _readRawLine() {
    return inputString[currentLine++];
}
function readLine() {
    // return _readRawLine().replace(/\s+$/g, '');
    return _readRawLine().replace("\r", "");
}

function print(x) {
    console.log(x);
}

function readSingleInt() {
    const p = readLine();
    return parseInt(p);
}

function readIntArray() {
    return readLine()
        .split(" ")
        .map((v) => parseInt(v));
}

function readArray() {
    return readLine().split(" ");
}

function int(n) {
    return parseInt(n);
}
/********** Utility Functions End **********/
/**
 * Don't Touch this fucntion at all , unless you know what are you doing!
 */
function main() {
    solve();
}

// ********** actual Code Starts from here **********

function isPalindromeTime(timeStr = '')
{
    const revStr = timeStr.split('').reverse().join('');
    return (revStr==timeStr );
}
function convertTime(n){
    let hour = Math.floor(n/60)%24;
    n = n%60;
    if(hour<10){
        hour = `0${hour}`;
    }
    if(n<10){
        n = `0${n}`;
    }
    return `${hour}:${n}`;
}
function solve() {
   let t= readSingleInt();
   while(t--)
   {
       let [timeString,interval]=  readLine().split(' ');
       interval = parseInt(interval);
       let [hour ,min] = timeString.split(':').map( v=> parseInt(v));
       let time = hour*60 + min;
        let ans =0;
        let list = new Set();
        if(isPalindromeTime(timeString)){
            ans++;
            list.add(timeString);
        }
       for(let i=time+interval;i<90*24*60;i+=interval){
            // console.log('hi')
            const cvs = convertTime(i) ;
            // if(cvs==timeString){
            //     break;
            // }
            let res =  isPalindromeTime( convertTime(i) );
            // console.log(cvs)
            if(res){
                ans++;
                list.add(cvs);
                // console.log(cvs)
            }
       }

    //    palindromeTimeList()
    //    console.log(isPalindromeTime('07:57'))
       console.log(list.size)

   }
}

/**
 * Author : Fazlul Hoque
 * Node.js version : 12.16.3
 * command : node fileName.js <input.txt >output.txt
 */
"use strict";
process.stdin.resume();
process.stdin.setEncoding("utf-8");
let inputString = ""; //An array of  raw inputs (includes 'n,\r , not usable. need to process before use)
let currentLine = 0; //input sequence controller variable.

process.stdin.on("data", (inputStdin) => {
    inputString += inputStdin;
});
process.stdin.on("end", () => {
    inputString = inputString.split("\n");
    main(); // after input
});

/********** Utility Functions Start **********/
/**
 *  read row Input
 * @returns string
 */
function _readRawLine() {
    return inputString[currentLine++];
}
function readLine() {
    // return _readRawLine().replace(/\s+$/g, '');
    return _readRawLine().replace("\r", "");
}

function print(x) {
    console.log(x);
}

function readSingleInt() {
    const p = readLine();
    return parseInt(p);
}

function readIntArray() {
    return readLine()
        .split(" ")
        .map((v) => parseInt(v));
}

function readArray() {
    return readLine().split(" ");
}

function int(n) {
    return parseInt(n);
}
/********** Utility Functions End **********/
/**
 * Don't Touch this fucntion at all , unless you know what are you doing!
 */
function main() {
    solve();
}

// ********** actual Code Starts from here **********

function isPalindromeTime(timeStr = '')
{
    const revStr = timeStr.split('').reverse().join('');
    return (revStr==timeStr );
}
function convertTime(n){
    let hour = Math.floor(n/60)%24;
    n = n%60;
    if(hour<10){
        hour = `0${hour}`;
    }
    if(n<10){
        n = `0${n}`;
    }
    return `${hour}:${n}`;
}
function solve() {
   let t= readSingleInt();
   while(t--)
   {
       let [timeString,interval]=  readLine().split(' ');
       interval = parseInt(interval);
       let [hour ,min] = timeString.split(':').map( v=> parseInt(v));
       let time = hour*60 + min;
        let ans =0;
        let list = new Set();
        if(isPalindromeTime(timeString)){
            ans++;
            list.add(timeString);
        }
       for(let i=time+interval;i<60*24*60;i+=interval){
            // console.log('hi')
            const cvs = convertTime(i) ;
            // if(cvs==timeString){
            //     break;
            // }
            let res =  isPalindromeTime( convertTime(i) );
            // console.log(cvs)
            if(res){
                ans++;
                list.add(cvs);
                // console.log(cvs)
            }
       }

    //    palindromeTimeList()
    //    console.log(isPalindromeTime('07:57'))
       console.log(list.size)

   }
}

/**
 * Author : Fazlul Hoque
 * Node.js version : 12.16.3
 * command : node fileName.js <input.txt >output.txt
 */
"use strict";
process.stdin.resume();
process.stdin.setEncoding("utf-8");
let inputString = ""; //An array of  raw inputs (includes 'n,\r , not usable. need to process before use)
let currentLine = 0; //input sequence controller variable.

process.stdin.on("data", (inputStdin) => {
    inputString += inputStdin;
});
process.stdin.on("end", () => {
    inputString = inputString.split("\n");
    main(); // after input
});

/********** Utility Functions Start **********/
/**
 *  read row Input
 * @returns string
 */
function _readRawLine() {
    return inputString[currentLine++];
}
function readLine() {
    // return _readRawLine().replace(/\s+$/g, '');
    return _readRawLine().replace("\r", "");
}

function print(x) {
    console.log(x);
}

function readSingleInt() {
    const p = readLine();
    return parseInt(p);
}

function readIntArray() {
    return readLine()
        .split(" ")
        .map((v) => parseInt(v));
}

function readArray() {
    return readLine().split(" ");
}

function int(n) {
    return parseInt(n);
}
/********** Utility Functions End **********/
/**
 * Don't Touch this fucntion at all , unless you know what are you doing!
 */
function main() {
    solve();
}

// ********** actual Code Starts from here **********

function isPalindromeTime(timeStr = '')
{
    const revStr = timeStr.split('').reverse().join('');
    return (revStr==timeStr );
}
function convertTime(n){
    let hour = Math.floor(n/60)%24;
    n = n%60;
    if(hour<10){
        hour = `0${hour}`;
    }
    if(n<10){
        n = `0${n}`;
    }
    return `${hour}:${n}`;
}
function solve() {
   let t= readSingleInt();
   while(t--)
   {
       let [timeString,interval]=  readLine().split(' ');
       interval = parseInt(interval);
       let [hour ,min] = timeString.split(':').map( v=> parseInt(v));
       let time = hour*60 + min;
        let ans =0;
        let list = new Set();
        if(isPalindromeTime(timeString)){
            ans++;
            list.add(timeString);
        }
       for(let i=time+interval;i<30*24*60;i+=interval){
            // console.log('hi')
            const cvs = convertTime(i) ;
            // if(cvs==timeString){
            //     break;
            // }
            let res =  isPalindromeTime( convertTime(i) );
            // console.log(cvs)
            if(res){
                ans++;
                list.add(cvs);
                // console.log(cvs)
            }
       }

    //    palindromeTimeList()
    //    console.log(isPalindromeTime('07:57'))
       console.log(list.size)

   }
}

/*
** 799D
*/

// Common Template Starts //
//*
process.stdin.resume();
process.stdin.setEncoding("utf-8");

let is = "";
let cl = 0;

process.stdin.on("data", (inp) => {
    is += inp;
});

process.stdin.on("end", (_) => {
    is = is.trim().split("\n").map((s) => s.trim());
    main();
});

const readline = () => is[cl++];

// Common Template Ends //

const isPalindrome = (n) => {
  const m = n % 60;
  const h = (n - m) / 60;
  const h1 = h % 10;
  const h0 = (h - h1) / 10;
  return `${h1}${h0}` === `${m < 10 ? '0' : ''}${m}`;
}

const toTime = (hhmm) => {
  const [h, m] = hhmm.split(':').map(n => parseInt(n));
  return h * 60 + m;
}

function main() {
  let nLines = parseInt(readline());
  while(nLines--) {
    const [time, x] = readline().split(' ');
    const start = toTime(time);
    const min = parseInt(x);
    let current = start + min;
    let n = isPalindrome(start) ? 1 : 0;
    while (current !== start) {
      if (isPalindrome(current)) n++;
      current = (current + min) % 1440;
    }

    console.log(n);
  }
}

const palindromes = [
    "00:00",
    "01:10",
    "02:20",
    "03:30",
    "04:40",
    "05:50",
    "10:01",
    "11:11",
    "12:21",
    "13:31",
    "14:41",
    "15:51",
    "20:02",
    "21:12",
    "22:22",
    "23:32",
];

const timeToMm = (v) => {
    const [hh, mm] = v.split(":").map(t => parseInt(t));
    return hh * 60 + mm;
};

const palindromeMinutes = palindromes.map(timeToMm);

// taken from https://codeforces.com/contest/1692/submission/170087380
const solve = () => {
    const [time, incrementStr] = readline().split(" ");
    const startTimeMm = timeToMm(time);
    const increment = parseInt(incrementStr);
    let answer = 0;
    let running = startTimeMm;
    const s = new Set();
    const pad = (v) => ("0" + v).substr(-2);
    const isPalindrome = (a) => a === a.split("").reverse().join("");
    while (true) {
        const timeToCheck = pad(Math.floor(running / 60)) + ":" + pad(running % 60);
        if (s.has(timeToCheck))
            break;

        if (isPalindrome(timeToCheck))
            answer++;

        s.add(timeToCheck);

        running += increment;
        running %= 1440;
    }
    console.log(answer);
}

/*
const gcd = (a, b) => {
    if (b == 0) {
        return a;
    }
    return gcd(b, a % b);
};

const lcm = (a, b) => a * b / gcd(a, b);

const solve = () => {
    const [time, incrementStr] = readline().split(" ");
    print(`time ${time}`);
    print(`incrementStr ${incrementStr}`);
    const startTimeMm = timeToMm(time);
    const increment = parseInt(incrementStr);
    print(`startTimeMm ${startTimeMm}`);
    let counter = 0;
    for (const palindromeTime of palindromeMinutes) {
        if ((lcm(palindromeTime, startTimeMm) - startTimeMm) % increment == 0)
            counter++;
    }
    print(counter);
};
*/

const main = () => {
    const t = parseInt(readline());
    for (let i = 0; i < t; i++) {
        solve();
    }
};


var i, r,
	n = +readline(),
	a = [],
	b = [],
	ans = -1;

for (var i = 1; i <= n; i++)
	readline().split(' ').map(Number).reduce(function(l, r) {
		a.push(l);
		b.push(r);
	});

var min = Math.min.apply(0, a);
var max = Math.max.apply(0, b);

for(i = 0; i<n; i++)
	if (min === a[i] && max === b[i])
		ans = i + 1;

print(ans);

'use strict';

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++];
}

// Make a Snippet for the code above this and then write your logic in main()
function main() {
  const numsOfInput = readline();
  let coordinates = []
  for (let i = 0; i < numsOfInput; i++) {
    const coordinate = readline().split(' ').map(segment => parseInt(segment));

    coordinates.push([...coordinate])
  }

  helper(coordinates);
}

function helper(coordinates) {
    let [minL, maxR] = coordinates[0];
    let index = 0;

    for (let i = 1; i < coordinates.length; i++) {
        const [l,r] = coordinates[i]
        if (l === minL) {
            if (r >= maxR) {
                maxR = r
                index = i
            }
        } else if (l < minL) {
            minL = l;
            if (r >= maxR) {
                maxR = r;
                index = i
            } else {
                index = -1;
            }
        } else {
            if (r > maxR) {
                maxR = r;
                index = -1;
            }
        }

    }

    console.log(index === -1 ? -1 : index + 1)
}

;(function () {

	print((function (n) {
		var _o = 1e10, o_ = -1, p = -1, l = n;

		while (l--) {
			var s = readline().split(' ').map(Number), _f = false, f_ = false;
			if (_o > s[0]) { _o = s[0]; _f = true; }
			if (o_ < s[1]) { o_ = s[1]; f_ = true; }
			if (_f || f_) p = -1;
			if (_o === s[0] && o_ === s[1]) p = n - l;
		}

		return p;
	})(+readline()));

}).call(this)

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 n = parseInt(readline()), segments = [];
	for (var i = 0; i < n; ++i) {
		var data = tokenizeIntegers(readline());
		segments.push({ left: data[0], right: data[1] });
	}
	var leftmost = segments[0].left, rightmost = segments[0].right;
	for (var i = 1; i < n; ++i) {
		leftmost = Math.min(leftmost, segments[i].left);
		rightmost = Math.max(rightmost, segments[i].right);
	}
	for (var i = 0; i < n; ++i) {
		if (segments[i].left == leftmost && segments[i].right == rightmost) {
			print(i+1);
			return;
		}
	}
	print(-1);
}

main();

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}
function pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}
function highestOneBit(i) {
  i |= i >> 1;
  i |= i >> 2;
  i |= i >> 4;
  i |= i >> 8;
  i |= i >> 16;
  return i - (i >>> 1);
}
function permutation(arr, len, store = "", permutations = []) {
  if (store.length === len) {
    permutations.push(store);
    return;
  }
  for (let i = 0; i < arr.length; i++) {
    const newArr = [...arr];
    const newChar = newArr.splice(i, 1);
    permutation(newArr, len, store.concat(newChar), permutations);
  }
  return permutations;
}

function main() {
  let len = +readLine();
  const arr = [];
  const map = new Map();
  let max = -Infinity;
  for (let i = 0; i < len; i++) {
    const row = readLine()
      .split(" ")
      .map((n) => parseInt(n));
    map.set(`${row[0]}_${row[1]}`, i + 1);
    max = Math.max(max, row[1]);
    arr.push(row);
  }

  arr.sort((a, b) => a[0] - b[0] || b[1] - a[1]);
  if (arr[0][1] >= max) console.log(map.get(`${arr[0][0]}_${arr[0][1]}`));
  else console.log(-1);
}

var n = +readline(),
	ans = -1,
	min = 1e10,
	max = 0;

for (var i = 1; i <= n; i++)
	(function(l, r) {
		var f = 0;
		if (l < min || r > max)
			ans = -1;

		if (l <= min) {
			f++;
			min = l;
		}
		if (r >= max) {
			f++;
			max = r;
		}

		if (f === 2)
			ans = i;

	}).apply(0, readline().split(' ').map(Number));

print(ans);

var i, r,
	n = +readline(),
	a = [],
	ans = -1;

for (var i = 1; i <= n; i++)
	a.push(readline().split(' ').map(Number));

r = a.reduce(function(a, b) {
	return [Math.min(a[0], b[0]), Math.max(a[1], b[1])];
});

a.forEach(function(v, i) {
	if (r[0] === v[0] && r[1] === v[1]) ans = i + 1;
});

print(ans);

'use strict';

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++];
}

// Make a Snippet for the code above this and then write your logic in main()
function main() {
  const numsOfInput = readline();
  let coordinates = []
  for (let i = 0; i < numsOfInput; i++) {
    const coordinate = readline().split(' ').map(segment => parseInt(segment));

    coordinates.push([...coordinate])
  }

  helper(coordinates);
}

function helper(coordinates) {
    let minL = coordinates[0][0];
    let maxR = coordinates[0][1];
    let index = 0;

    for (let i = 1; i < coordinates.length; i++) {
        const [l,r] = coordinates[i]
        if (l <= minL) {
            minL = l;
            if (r >= maxR) {
                maxR = r;
                index = i
            } else {
                index = -1;
            }
        } else {
            if (r > maxR) {
                maxR = r;
                index = -1;
            }
        }

    }

    console.log(index === -1 ? -1 : index + 1)
}

'use strict';

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++];
}

// Make a Snippet for the code above this and then write your logic in main()
function main() {
  const numsOfInput = readline();
  let coordinates = []
  for (let i = 0; i < numsOfInput; i++) {
    const coordinate = readline().split(' ').map(segment => parseInt(segment));

    coordinates.push([...coordinate])
  }

  helper(coordinates);
}

function helper(coordinates) {
  let minL = coordinates[0][0]
  let maxR = coordinates[0][1]
  let index = 0

  for (let i = 1; i < coordinates.length; i++) {
    if (coordinates[i][0] <= minL && coordinates[i][1] >= maxR) {
        index = i;
    }
    if (coordinates[i][0] <= minL)
        minL = coordinates[i][0]
    if (coordinates[i][1] <= maxR)
        maxR = coordinates[i][1]
  }

  if (index === 0 && minL === maxR) {
    console.log(-1)
    return
  }
  console.log(index + 1)

}

'use strict';

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++];
}

// Make a Snippet for the code above this and then write your logic in main()
function main() {
  const numsOfInput = readline();
  let coordinates = []
  for (let i = 0; i < numsOfInput; i++) {
    const coordinate = readline().split(' ').map(segment => parseInt(segment));

    coordinates.push([...coordinate])
  }

  helper(coordinates);
}

function helper(coordinates) {
    let [minL, maxR] = coordinates[0];
    let index = 0;

    for (let i = 1; i < coordinates.length; i++) {
        const [l,r] = coordinates[i]
        if (l === minL) {
            if (r >= maxR) {
                maxR = r
                index = i
            }
        } else if (l < minL) {
            minL = l;
            if (r >= maxR) {
                maxR = r;
                index = i
            } else {
                index = -1;
            }
        } else {
            if (r >= maxR) {
                maxR = r;
                index = -1;
            }
        }

    }

    console.log(index === -1 ? -1 : index + 1)
}

'use strict';

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++];
}

// Make a Snippet for the code above this and then write your logic in main()
function main() {
  const numsOfInput = readline();
  let coordinates = []
  for (let i = 0; i < numsOfInput; i++) {
    const coordinate = readline().split(' ').map(segment => parseInt(segment));

    coordinates.push([...coordinate])
  }

  helper(coordinates);
}

function helper(coordinates) {
    let minL = Number.MAX_VALUE
    let maxR = Number.MIN_VALE
    let index = -1;

    for (let i = 0; i < coordinates.length; i++) {
        const [l,r] = coordinates[i]

        if (l <= minL) {
            minL = l
            index = -1
        }

        if (r >= maxR) {
            maxR = r
            index = -1
        }

        if (l === minL && r === maxR) {
            index = i
        }
    }

    console.log(index === -1 ? -1 : index + 1)
}

'use strict';

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++];
}

// Make a Snippet for the code above this and then write your logic in main()
function main() {
  const numsOfInput = readline();
  let coordinates = []
  for (let i = 0; i < numsOfInput; i++) {
    const coordinate = readline().split(' ').map(segment => parseInt(segment));

    coordinates.push([...coordinate])
  }

  helper(coordinates);
}

function helper(coordinates) {
    let [minL, maxR] = coordinates[0];
    let index = 0;

    for (let i = 1; i < coordinates.length; i++) {
        const [l,r] = coordinates[i]
        if (l === minL) {
            if (r > maxR) {
                maxR = r
                index = i
            }
        } else if (l < minL) {
            minL = l;
            if (r >= maxR) {
                maxR = r;
                index = i
            } else {
                index = -1;
            }
        } else {
            if (r > maxR) {
                maxR = r;
                index = -1;
            }
        }

    }

    console.log(index === -1 ? -1 : index + 1)
}

'use strict';

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++];
}

// Make a Snippet for the code above this and then write your logic in main()
function main() {
  const numsOfInput = readline();
  let coordinates = []
  for (let i = 0; i < numsOfInput; i++) {
    const coordinate = readline().split(' ').map(segment => parseInt(segment));

    coordinates.push([...coordinate])
  }

  helper(coordinates);
}

function helper(coordinates) {
  let minL = coordinates[0][0]
  let maxR = coordinates[0][1]
  let index = 0

  for (let i = 1; i < coordinates.length; i++) {
    if (coordinates[i][0] <= minL && coordinates[i][1] >= maxR) {
        index = i;
    }
  }

  if (index === 0 && minL === maxR) {
    console.log(-1)
    return
  }
  console.log(index + 1)

}

'use strict';

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++];
}

// Make a Snippet for the code above this and then write your logic in main()
function main() {
  const numsOfInput = readline();
  let coordinates = []
  for (let i = 0; i < numsOfInput; i++) {
    const coordinate = readline().split(' ').map(segment => parseInt(segment));

    coordinates.push([...coordinate])
  }

  helper(coordinates);
}

function helper(coordinates) {
    let [minL, maxR] = coordinates[0];
    let index = 0;

    for (let i = 1; i < coordinates.length; i++) {
        const [l,r] = coordinates[i]
        if (l === minL) {
            if (r > maxR) {
                maxR = r
                index = -1
            }
        } else if (l < minL) {
            minL = l;
            if (r >= maxR) {
                maxR = r;
                index = i
            } else {
                index = -1;
            }
        } else {
            if (r > maxR) {
                maxR = r;
                index = -1;
            }
        }

    }

    console.log(index === -1 ? -1 : index + 1)
}

'use strict';

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++];
}

// Make a Snippet for the code above this and then write your logic in main()
function main() {
  const numsOfInput = readline();
  let coordinates = []
  for (let i = 0; i < numsOfInput; i++) {
    const coordinate = readline().split(' ').map(segment => parseInt(segment));

    coordinates.push([...coordinate])
  }

  helper(coordinates);
}

function helper(coordinates) {
  let minL = coordinates[0][0]
  let maxR = coordinates[0][1]
  let index = 0

  for (let i = 1; i < coordinates.length; i++) {
    if (coordinates[i][0] <= minL && coordinates[i][1] >= maxR) {
        index = i;
    }
    if (coordinates[i][0] <= minL)
        minL = coordinates[i][0]
    if (coordinates[i][1] >= maxR)
        maxR = coordinates[i][1]
  }

  if (index === 0 && minL === maxR) {
    console.log(-1)
    return
  }
  console.log(index + 1)

}

var n = +readline(),
	ans = -1,
	min = 1e10,
	max = 0;

for (var i = 1; i <= n; i++)
	(function(l, r) {
		var f = 0;
		if (l <= min) {
			f++;
			min = l;
		}
		if (r >= max) {
			f++;
			max = r;
		}
		if (f === 2) {
			ans = i;
		}
	}).apply(0, readline().split(' ').map(Number));

print(ans);

var n = +readline(),
	ans = -1,
	min = 1e10,
	max = 0;

for (var i = 1; i <= n; i++)
	(function(l, r) {
		var f = 0;
		if (l <= min) {
			f++;
			min = l;
		}
		if (r >= max) {
			f++;
			max = r;
		}

		if (f === 2)
			ans = i;
		else if (f === 1)
			ans = -1;

	}).apply(0, readline().split(' ').map(Number));

print(ans);

var n = +readline(),
	ans = -1,
	min = 1e10,
	max = 0;

for (var i = 1; i <= n; i++)
	(function(l, r) {
		var f = 0;
		if (l <= min) {
			f++;
			min = l;
		}
		if (r >= max) {
			f++;
			max = r;
		}

		if (f === 2)
			ans = i;
		if (l < min || r > max)
			ans = -1;

	}).apply(0, readline().split(' ').map(Number));

print(ans);

;(function () {

	print((function (n) {
		var _o = 1e5, o_ = 0, p = -1, l = n;

		while (l--) {
			var s = readline().split(' ').map(Number), _f = false, f_ = false;
			if (_o > s[0]) { _o = s[0]; _f = true; }
			if (o_ < s[1]) { o_ = s[1]; f_ = true; }
			if (_f || f_) p = -1;
			if (_o === s[0] && o_ === s[1]) p = n - l;
		}

		return p;
	})(+readline()));

}).call(this)

;(function () {

	print((function (n) {
		var a = [], min = 1e6, max = 0;

		for (var i = 0; i < n; i++) {
			var s = readline().split(' ').map(Number);
			min = Math.min(min, s[0]);
			max = Math.max(max, s[1]);
			a.push(s);
		}

		for (var i = 0; i < n; i++) if (a[i][0] === min && a[i][1] === max) return i + 1;
		return -1;
	})(+readline()));

}).call(this)


var num = parseInt(readline());
var field = [];

field.push(Array(num + 3).join(".").split(""));
for(var i=0; i < num; i++) field.push(("." + readline() + ".").split(""));
field.push(Array(num + 3).join(".").split(""));

var txt = field.join(""), c = 0, col = 0, need = 0;
for(var i in txt) if(txt[i] == '#') c++;

need = c / 5;

function check(y, x){

    if (field[y][x] == "." &&
        field[y][x+1] == "#" &&
        field[y+1][x] == "#" &&
        field[y+1][x+1] == "#" &&
        field[y+1][x+2] == "#" &&
        field[y+2][x+1] == "#"
    ) {

        field[y][x + 1] = ".";
        field[y + 1][x + 1] = ".";
        field[y + 2][x + 1] = ".";
        field[y + 1][x] = ".";
        field[y + 1][x + 2] = ".";
        col++;
    }
}

if (c % 5 != 0) print("NO");
else {

    for(var i = 1; i <= num; i++) {
        for(var j = 1; j <= num; j++) {
            check(i, j);
        }
    }

    if (need == col) print("YES");
    else print("NO");
}

function sort(a, b){if (a == b) return 0; return a > b ? 1 : -1}
function sort2(a, b){if (a == b) return 0; return a < b ? 1 : -1}

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]);
	};
	return tokens;
}

function main() {
	var n = parseInt(readline());

	var grid = [];
	for (var r = 0; r < n; ++r) {
		grid.push(trim(readline()).split(''));
	}

	var dr = [0, 1, 1, 1, 2], dc = [1, 0, 1, 2, 1];

	function diagonal(r, c) {
		if (r+2 < n && c+2 < n) {
			var match = true;
			for (var i = 0; i < 5; ++i) {
				if (grid[r+dr[i]][c+dc[i]] == '.') {
					match = false;
				}
			}
			if (match) {
				for (var i = 0; i < 5; ++i) {
					grid[r+dr[i]][c+dc[i]] = '.';
				}
			}
		}
		if (r != 0 && c != n-1) {
			diagonal(r-1, c+1);
		}
	}

	for (var r = 0; r < n; ++r) {
		diagonal(r, 0);
	}
	for (var c = 0; c < n; ++c) {
		diagonal(n-1, c);
	}

	for (var r = 0; r < n; ++r) {
		for (var c = 0; c < n; ++c) {
			if (grid[r][c] == '#') {
				print("NO");
				return;
			}
		}
	}
	print("YES");
}

main();

var n = parseInt(readline(), 10);
var seqs = [];
var i, x, y;

for (i = 0; i < n; i++) {
  seqs.push(readline().split(""));
}

for (y = 0; y < n; y++) {
  for (x = 0; x < seqs[y].length; x++) {
    if (seqs[y][x] == "#") {
      if (y != 0 && x != 0 && x != seqs[y].length - 1 && y != n - 1) {
        if (seqs[y - 1][x] == "#" && seqs[y][x - 1] == "#"
            && seqs[y + 1][x] == "#" && seqs[y][x + 1] == "#") {
          seqs[y][x + 1] = "x";
          seqs[y][x - 1] = "x";
          seqs[y + 1][x] = "x";
          seqs[y - 1][x] = "x";
          seqs[y][x] = "x";
        }
      }
    }
  }
}

var result = true;
for (y = 0; y < n; y++) {
  for (x = 0; x < seqs[y].length; x++) {
    if (seqs[y][x] == "#") {
      result = false;
      break;
    }
  }

  if (!result) {
    break;
  }
}

if (result) {
  print("YES");
} else {
  print("NO");
}


"use strict";

var n = parseInt(readline());
var arr = [];

for (var i = 0; i < n; i++) {
  var str = '';

  if (i % 2 === 1) {
    str += 'W';
  } else {
    str += 'B';
  }

  for (var j = 1; j < n; j++) {
    if (str[j - 1] === 'B') {
      str += 'W';
    } else {
      str += 'B';
    }
  }

  arr.push(str);
}

write(arr.join('\n'));

"use strict";

var n = parseInt(readline());
var arr = [];

for(var i=0 ; i<n ; i++){
    var str = '';
    if(i%2===1) {
        str+='W';
    }
    else {
        str+='B';
    }

    for(var j =1 ; j<n ; j++){
        if(str[j-1]==='B'){
            str+='W';
        }else {
            str+='B';
        }
    }

    arr.push(str);
}

write(arr.join('\n'));

const process = require('process');

let inp = "";
process.stdin.on('data', chunk => inp += chunk);
process.stdin.on('end', () => {
    const n = +inp;
    let u = "";
    let v = "";
    for (let i = 0; i < n; ++i) {
        u += 'W';
        v += 'B';
        [u, v] = [v, u];
    }
    for (let i = 0; i < n; ++i)
        console.log(i % 2 === 1 ? u : v);
});


'use strict';

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

let inputString = '';
let currentLine = 0;

process.stdin.on('data', stdin => inputString += stdin);

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(s => s.trim());
    main();
});

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

function output(x) {
    if (typeof x !== 'string') {
        x = x.toString();
    }
    //process.stdout.write(x);   // without auto '\n' (newline)
    console.log(x);  // with auto '\n' (newline)
}

function main() {
    let N = readline();

    for (let test = 0; test < N; test++) {
        let [l,r,k] = readline().split(' ').map(Number);
        if (l === r) {
            output(l === 1 ? 'NO': 'YES');
            continue;
        }
        let ol = l % 2 === 1 ? l : l + 1;
        let or = r % 2 === 1 ? r : r - 1;
        let odd = ((or - ol) / 2) + 1;
        output(odd <= k ? 'YES': 'NO');
    }
}

const fs = require('fs');
const input = fs.readFileSync(0, 'utf8').trim().split('\n');
let currentline = 0;
function readline(){
    return input[currentline++];
}

var T = readline();
for(var q=1;q<=T;q++) {
            var [l,r,k] = readline().split(" ").map(w => parseInt(w))
            console.log(solve())
        	function solve() {
        		var n = (r-l)+1;
        		if(k == 0) {
        			if(n > 1) return 'NO'
        			else {
        				if(l == 1) return 'NO'
        				else return 'YES'
        			}
        		}
        		var sum = (r-l)+1;
        		if(sum %2 == 0) sum /= 2;
        		else {
        			if(l%2 == 0) sum = 1 + Math.floor(sum/2);
        			else sum = Math.floor(sum/2)
        		}

        		var odd = n-sum;
        		if(odd < k+1) return 'YES';
        		else return 'NO'
        	}
}

let y = '';
process.stdin.on('data', c => y += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = y.split(EOL);
	var t = lines[0];
	for(i = 1; i <= t; i++){
	    var a = lines[i].split(' ').map(Number);
	    var l = a[0], r = a[1], k = a[2];
	    if(l == r){
	        if(l > 1){
	            console.log('YES');
	        }else{
	            console.log('NO');
	        }
	    }else{
	        var odd = Math.floor((r - l + 1) / 2);
	        var even = Math.ceil((r - l + 1) / 2);
	        if(r % 2 == l % 2){
	            if(r % 2 == 1){
	                odd++;
	            }else{
	                even++;
	            }
	        }
	        if(k >= odd){
	            console.log('YES');
	        }else{
	            console.log('NO');
	        }
	    }
	}
});

// Common Template Starts //
//*
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++];
}
// Common Template Ends //

// LIBRARY START //

const isOdd = (x) => {
  return x & 1;
};
const isEven = (x) => {
  return !(x & 1);
};

const reverseText = (s) => {
  return s.split("").reverse().join("");
};
const hasDuplicates = (str) => /([a-z])\1/i.test(str);

const hasDuplicateChar = (str, char) =>
  str.indexOf(char) !== str.lastIndexOf(char);

const isSorted = (arr) => arr.every((v, i, a) => !i || a[i - 1] <= v);

const findAllIndicesOfChar = (str, char) => {
  str = str.split("");
  let indices = [];
  for (let i = 0; i < str.length; i++) {
    if (str[i] === char) indices.push(i);
  }
  return indices;
};

const splitAt = (index) => (x) => [x.slice(0, index), x.slice(index)];

const isUpper = (str) => !/[a-z]/.test(str) && /[A-Z]/.test(str);

const escapeRegExp = (string) =>
  string.replace(/[.*+\-?^$$${}()|[\]\\]/g, "$$$&");

const replaceAll = (str, find, replace) =>
  str.replace(new RegExp(escapeRegExp(find), "g"), replace);

const findUnique = (str) => {
  return [...str].reduce((acc, curr) => {
    return acc.includes(curr) ? acc : acc + curr;
  }, "");
};

const unique = (str) => {
  const cleanStr = str.replace(/ /gi, "");
  const set = [...new Set(cleanStr)];
  return set;
};

const sortASC = (array) => {
  // var numArray = new Uint32Array(array)
  // var numArray = new Int32Array(array)
  var numArray = new Float64Array(array);
  numArray = numArray.sort();
  return numArray;
};

const removeDuplicates = (array) => [...new Set(array)];

// LIBRARY END

function solve() {
  let [l, r, k] = readline().split(" ").map(Number);
  if (l == 1 && r == 1) {
    console.log("NO");
    return;
  }

  if (l == r) {
    console.log("YES");
    return;
  }

  let minMoves = (r - l + 1) - ( Math.floor(r/2) - Math.floor((l-1)/2));
  if(minMoves <= k){
    console.log("YES");
  }
  else{
    console.log("NO");
  }
}

function main() {
  let tc = +readline();
  while (tc--) {
    solve();
  }
}

let y = '';
process.stdin.on('data', c => y += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = y.split(EOL);
	var t = lines[0];
	for(i = 1; i <= t; i++){
	    var a = lines[i].split(' ').map(Number);
	    var l = a[0], r = a[1], k = a[2];
	    if(l == r){
	        if(l > 1){
	            console.log('YES');
	        }else{
	            console.log('NO');
	        }
	    }else{
	        var odd = Math.floor((r - l + 1) / 2);
	        var even = Math.floor((r - l + 1) / 2);
	        if(r % 2 == 1){
	            odd++;
	        }else{
	            even++;
	           }
	        if(k >= odd){
	            console.log('YES');
	        }else{
	            console.log('NO');
	        }
	    }
	}
});

// Common Template Starts //
//*
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++];
}
// Common Template Ends //

// LIBRARY START //

const isOdd = (x) => {
  return x & 1;
};
const isEven = (x) => {
  return !(x & 1);
};

const reverseText = (s) => {
  return s.split("").reverse().join("");
};
const hasDuplicates = (str) => /([a-z])\1/i.test(str);

const hasDuplicateChar = (str, char) =>
  str.indexOf(char) !== str.lastIndexOf(char);

const isSorted = (arr) => arr.every((v, i, a) => !i || a[i - 1] <= v);

const findAllIndicesOfChar = (str, char) => {
  str = str.split("");
  let indices = [];
  for (let i = 0; i < str.length; i++) {
    if (str[i] === char) indices.push(i);
  }
  return indices;
};

const splitAt = (index) => (x) => [x.slice(0, index), x.slice(index)];

const isUpper = (str) => !/[a-z]/.test(str) && /[A-Z]/.test(str);

const escapeRegExp = (string) =>
  string.replace(/[.*+\-?^$$${}()|[\]\\]/g, "$$$&");

const replaceAll = (str, find, replace) =>
  str.replace(new RegExp(escapeRegExp(find), "g"), replace);

const findUnique = (str) => {
  return [...str].reduce((acc, curr) => {
    return acc.includes(curr) ? acc : acc + curr;
  }, "");
};

const unique = (str) => {
  const cleanStr = str.replace(/ /gi, "");
  const set = [...new Set(cleanStr)];
  return set;
};

const sortASC = (array) => {
  // var numArray = new Uint32Array(array)
  // var numArray = new Int32Array(array)
  var numArray = new Float64Array(array);
  numArray = numArray.sort();
  return numArray;
};

const removeDuplicates = (array) => [...new Set(array)];

// LIBRARY END

function solve() {
  let [l, r, k] = readline().split(" ").map(Number);

  if (l == 1 && r == 1) {
    console.log("NO");
    return;
  }

  if (l == r) {
    console.log("YES");
    return;
  }

  let minMoves = r - l + 1 - (r / 2 - (l - 1) / 2);
  let ans = minMoves <= k ? "YES" : "NO";
  console.log(ans);
}

function main() {
  let tc = +readline();
  while (tc--) {
    solve();
  }
}


'use strict';

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.replace(/\s*$/, '')
        .split('\n')
        .map(str => str.replace(/\s*$/, ''));

    main();
});

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

function main() {
    let nm = readLine().split(' ').map(value => parseInt(value))
    let n = nm[0];
    let m = nm[1];
    let oke = 1;
    for (var i = 0; i < n; i++) {
        if (i % 2 == 0) {
            console.log('#'.repeat(m))
        } else {
            if (oke % 2 == 1) {
                console.log('.'.repeat(m - 1) + '#')
                oke++;
            } else {
                console.log('#' + '.'.repeat(m - 1))
                oke++;
            }
        }
    }
}

function answer(input){
    input = input.split(' ');
    var n = input[0];
    var m = input[1];
    var emptyLine = '';
    for(var i = 0; i < m; i++){
        emptyLine += '.';
    }
    var fullLine = emptyLine.replace(/\./g,'#');
    var snakeSideLine = emptyLine.slice(0,-1);
    var rightSnake = snakeSideLine+'#';
    var leftSnake = '#'+snakeSideLine;
    var output = [];
    var steps = [fullLine,rightSnake,fullLine,leftSnake];

    for(var i = 0; i < n; i++){
        output.push(steps[i%4]);
    }
    output.forEach(function(el){
        print(el);
    });
}

answer(readline());

var line = readline().split(" ");
var n = parseInt(line[0]);
var m = parseInt(line[1]);
for (var i = 0; i < n; i++) {
    if ((i + 1) % 2 === 0) {
        if ((i + 1) % 4 === 0) {
            write("#");
            for (var j = 1; j < m; j++) {
                write(".");
            }
        } else {
            for (var j = 1; j < m; j++) {
                write(".");
            }
            write("#");
        }
    } else {
        for (var j = 0; j < m; j++) {
            write("#");
        }
    }
    write("\n");
}

///////////////////////////////////////////////////////////////////////////////
function readNumber () { return Number(readline()); }
function readNumbersArray () { return readline().split(' ').map(Number); }
function algebraicSum (startValue, finishValue, size) { return (startValue + finishValue) * size / 2; }
///////////////////////////////////////////////////////////////////////////////

var array = readNumbersArray();
var n = array[0], m = array[1];

var a = '';
for (var i = 0; i < m; i++) a += '#';

var ba = '#';
for (var i = 1; i < m; i++) ba += '.';

var ab = '';
for (var i = 1; i < m; i++) ab += '.';
ab += '#';

var result = [];
for (var i = 0; i < n; i++) result.push(a);
for (var i = 1; i < n; i += 4) result[i] = ab;
for (var i = 3; i < n; i += 4) result[i] = ba;

print(result.join('\n'));

var s = readline().split(" ");
var n = Number(s[0]), m = Number(s[1]);
for(var i = 0; i<n; i++) {
    var str = '';
    for(var j = 0; j<m; j++) {
        if (i%2==0) {
            str = str + '#'
        }
        else if (i%4 == 1 && j == m-1) {
            str = str + '#'
        }
        else if (i%4 == 3 && j == 0) {
            str = str + '#'
        }
        else {
            str = str + '.'
        }
    }
    print(str);
}

function solve(){
    var input = readline().split(" ");
    var n = parseInt(input[0]);
    var m = parseInt(input[1]);
    var flag = 1;
    for(var i = 0; i < n; ++i){
        if(i % 2 == 0){
           print(Array(m + 1).join("#"));
        } else {
            flag = 1 - flag;
            if(flag){
                print("#" + Array(m).join("."));
            } else {
                print(Array(m).join(".") + "#");
            }
        }
    }
}
solve();

'use strict'
String.prototype.getNumArray = function () {
  return String(this).split(' ').map(function (value) {
    return parseInt(value);
  });
};

let array = readline().getNumArray(),
    n = array[0],
    m = array[1],
    empty = '.',
    filled = '#',
    snake = [],
    a = 0;

const isHashExist = (row) => row.indexOf('#') === -1;

for (let i = 0; i < n; i++) {
  let str = '';
  for (let j = 0; j < m; j++) {
    if (i % 2 === 0) {
      str += filled;
    } else {
      if (
        (a % 2 === 0 && j === m - 1 && isHashExist(str)) ||
        (a % 2 !== 0 && j === 0 && isHashExist(str))
        ) {
        str += filled;
          a++;
      } else {
        str += empty;
      }
    }
  }
  snake.push(str);
}
for (let i = 0; i < snake.length; i++){
  write(snake[i] + '\n');
};

var main = function(n, m)
{
    var arrHelpToCreateTrueSnake = [], allInSharp = [], arrResult = [];
    for (var i = 1; i <= m; i++)
    {
        if (i !== 1) arrHelpToCreateTrueSnake.push('.');
        else arrHelpToCreateTrueSnake.push('#');
        allInSharp.push('#');
    }
    for (i = 1; i <= n; i++)
    {
        if (i % 2 === 1) print(allInSharp.join(''));
        else print(arrHelpToCreateTrueSnake.reverse().join(''));
    }
    return 0;
}
var input = readline();
input = input.split(' ');
main(+input[0], +input[1]);

var nm = readline().split(' ').map(Number);
var n = nm[0],
	m = nm[1];

var fullRow = Array.apply(null, new Array(m)).map(function () { return '#'; }).join('');
var turnLeft = Array.apply(null, new Array(m - 1)).map(function () { return '.'; }).join('') + '#';
var turnRight = turnLeft.split('').reverse().join('');

var dir = 'left';

for (var i = 0; i < n; i++) {
	if (i % 2 == 0) {
		print(fullRow);
	} else {
		if (dir == 'left') {
			print(turnLeft);
			dir = 'right';
		} else {
			print(turnRight);
			dir = 'left';
		}
	}
};

var inputs = readline().split(" ");
var n = inputs[1]
var m = inputs[0]
var r = 1;
var str = "";
for (var i = 0; i < m; i++) {
  for (var j = 0; j < n; j++) {
      if (i%2 == 0)
          str += "#";
      else {
          if (r==1) {
              if (j!=n-1)
                  str += ".";
              else
                  str += "#";
          }
          else if (r == 0) {
              if (j!=0)
                  str += ".";
              else
                  str += "#";
          }
      }
  }
  if (i%2 != 0) {
      if (r==1) r = 0;
      else r = 1;
  }
  str += '\n'
}
print(str)

var params = readline().split(" ").map(value => +value);
var n = params[0], m = params[1];
var full = first = last = "";

for(var i = 0; i < m; i++) {full += "#";}
first += "#";  for(var i = 0; i < m - 1; i++) {first += ".";}
for(var i = 0; i < m - 1; i++) {last += ".";} last += "#";

for(var i = 0; i < n; i++) {
	if ((i + 1) % 2 === 1)
		print(full);
	else if ((i + 1) % 4 === 0)
		print(first);
	else
		print(last);
}

"use strict";

var input = readline().split(' ').map(value => +value);
var n = input[0];
var m = input[1];

var a = new Array(m).fill('#').join('');
var b = new Array(m - 1).fill('.').join('') + '#';
var c = '#' + new Array(m - 1).fill('.').join('');

var d = [a, b, a, c];

for (let i = 0; i < n; ++i) {
    print(d[i % 4]);
}

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  console.error("\n");
  var start = Date.now();
  Main();
  var end = Date.now() - start;
  myerr("time : " + (end) + "ms");
  myerr("memory : " + Math.round(process.memoryUsage().heapTotal / 1024) + "KB");
});
function makeClone(obj){return JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
  return {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw "ArrayIndexOutOfBoundsException ‚There is no more input";}}
  };
}
function myout(s){console.log(s);}
function myerr(s){console.error("debug:" + require("util").inspect(s,false,null));}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map(Number);case 6:return i.split("");case 7:return i.split("").map(Number);case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
  var one = nextIntArray();
  var n = one[0];
  var m = one[1];
  var output = new Array(n);
  for(var i = 0; i < n; i++){
    if(i % 2 == 0){
      output[i] = new Array(m).fill("#").join("");
    }else{
      var tmp = new Array(m).fill(".");
      if(i % 4 == 1){
        tmp[m - 1] = "#";
      }else{
        tmp[0] = "#";
      }
      output[i] = tmp.join("");
    }
  }
  myout(myconv(output, 9));
}

const readline = require('readline');

let secondLine = false;

// Create readline Interface
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

let inputs = [];

rl.on('line', lineInput => {
    inputs.push(lineInput);
})

// Read Inputs
rl.on('close', () => {
    const line1 = inputs[0].split(' ');
    const rows = parseInt(line1[0]);
    const cols = parseInt(line1[1]);
    let snake = '';
    let turning = false;
    let direction = 'ltr';

    for (let i = 0; i < rows; i++) {
        for (let j = 0; j < cols; j++) {

            if (!turning) {
                snake += '#';
            } else {
                if (direction == 'rtl') {
                    if (j === cols - 1)
                        snake += '#';
                    else
                        snake += '.';
                } else {
                    if (j === 0)
                        snake += '#';
                    else
                        snake += '.';

                }
            }

        }

        if (!turning) {
            if (direction == 'rtl') {
                direction = 'ltr'
            } else {
                direction = 'rtl'
            }
        }

        turning = !turning;

        console.log(snake);
        snake = ''
    }

});

var input = readline().split(' ');var row = input[0];var coulmns = input[1];var result = "";var pin = 0;var pervious=0;

for (var i = 0; i < row; i++){

if (pin == 0){
	for(var s = 0; s < coulmns; s++){result+="#";}
 pin=1;print(result); result="";
  }else{

 for(var d = 0; d < (coulmns-1); d++){result+=".";}

 if(pervious == 0){result+="#";pervious="1";}else{result="#" + result;pervious="0";}
 pin=0;print(result);result="";}}

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

rl.on('line', (d) => {
  const [r, c] = d.split(' ').map(Number);
  let isStart = false;
  let body = '#';
  let empty = '.';

  for (let i = 0; i < r; i++) {
    let ans = '';
    for (let j = 0; j < c; j++) {
      if (i % 2 === 0) {
        ans += body;
      }
      else{
        ans += empty;
      }
    }

    if (i % 2 !== 0) {
      if (isStart) {
        ans = body + ans.slice(1);
      }
      else {
        ans = ans.slice(0, ans.length - 1) + body;
      }
      isStart = !isStart;
    }

    console.log(ans);
  }
});

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

rl.on('line', (d) => {
  const [r, c] = d.split(' ').map(Number);
  let isStart = false;
  let body = '#';
  let empty = '.';
  let ans;

  for (let i = 0; i < r; i++) {
    if (i % 2 === 0) {
      ans = body.repeat(c);
    }
    else {
      ans = isStart ? body + empty.repeat(c - 1) : empty.repeat(c - 1) + body;
      isStart = !isStart;
    }

    console.log(ans);
  }
});

let fs = require('fs');

let txt = fs.readFileSync(0, "utf-8").split(/[\n\r]/).filter(data => data.length > 0);

for (let i = 0; i < txt.length; i++) {
    let info = txt[i].split(" ");
    doit(info[0] * 1, info[1] * 1);
}

function doit(n, n1) {
    let drawing = "";
    for (let i = 1; i <= n; i++) {
        if (i % 2 == 1) {
            if (i != 1) {
                drawing = drawing.concat("\n");
                drawing = drawing.concat(new Array(n1).fill("#").join(""));
            } else {
                drawing = drawing.concat(new Array(n1).fill("#").join(""));
            }
        } else {
            drawing = drawing.concat("\n");
            if (i % 4 == 2) {
                drawing = drawing.concat(new Array(n1 - 1).fill(".").join(""));
                drawing = drawing.concat("#");
            } else {
                drawing = drawing.concat("#");
                drawing = drawing.concat(new Array(n1 - 1).fill(".").join(""));
            }
        }

    }
    console.log(drawing);

}

// Sample code to perform I/O:

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

process.stdin.on("data", function (input) {
    stdin_input += input;                               // Reading input from STDIN
});

process.stdin.on("end", function () {
    main(stdin_input);
});

function main(input) {
    let output = nameLookUp(input);
    process.stdout.write(output);       // Writing output to STDOUT
}

// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail

// Write your code here
function nameLookUp(str) {

    let inputs = str.trim().split(' ');
    let completeSnake = '';
    let track = true;
    let snakeEmptyCell = '';
    let snakeCell = '';
    for (let i = 1; i <= +inputs[0]; i++) {

        if (i % 2 !== 0) {
            snakeCell = "#".repeat(+inputs[1]);
            completeSnake += snakeCell + '\n';
        } else if (track) {
            snakeEmptyCell = ".".repeat(+inputs[1] - 1) + '#';
            track = false;
            completeSnake += snakeEmptyCell + '\n';
        }
        else {
            snakeEmptyCell = "#" + '.'.repeat(+inputs[1] - 1);
            track = true;
            completeSnake += snakeEmptyCell + '\n';
        }

    }

    return completeSnake.toString();
}

function answer(input){
    input = input.split(' ');
    var n = input[0];
    var m = input[1];
    var emptyLine = '';
    for(var i = 0; i < m; i++){
        emptyLine += '.';
    }
    var fullLine = emptyLine.replace('.','#');
    var snakeSideLine = emptyLine.slice(0,-1);
    var rightSnake = snakeSideLine+'#';
    var leftSnake = '#'+snakeSideLine;
    var output = [];
    var steps = [fullLine,leftSnake,fullLine,rightSnake];

    for(var i = 0; i < n; i++){
        output.push(steps[i%4]);
    }
    output.forEach(function(el){
        print(el);
    });
}

answer(readline());

///////////////////////////////////////////////////////////////////////////////
function readNumber () { return Number(readline()); }
function readNumbersArray () { return readline().split(' ').map(Number); }
function algebraicSum (startValue, finishValue, size) { return (startValue + finishValue) * size / 2; }
///////////////////////////////////////////////////////////////////////////////

var array = readNumbersArray();
var n = array[0], m = array[1];

var a = '';
for (var i = 0; i < m; i++) a += '#';

var ba = '#';
for (var i = 1; i < m; i++) ba += '-';

var ab = '';
for (var i = 1; i < m; i++) ab += '-';
ab += '#';

var result = [];
for (var i = 0; i < n; i++) result.push(a);
for (var i = 1; i < n; i += 4) result[i] = ab;
for (var i = 3; i < n; i += 4) result[i] = ba;

print(result.join('\n'));

'use strict'
String.prototype.getNumArray = function () {
  return String(this).split(' ').map(function (value) {
    return parseInt(value);
  });
};

let array = readline().getNumArray(),
    n = array[0],
    m = array[1],
    empty = '.',
    filled = '#',
    snake = [];

for (let i = 0; i < n; i++) {
  let str = '';
  for (let j = 0; j < m; j++) {
    if (i % 2 === 0) {
      str += filled;
    } else {
      if (j === m - 1) {
        str += filled;
      } else {
        str += empty;
      }
    }
  }
  snake.push(str);
}
for (let i = 0; i < snake.length; i++){
  write(snake[i] + '\n');
};

'use strict'
String.prototype.getNumArray = function () {
  return String(this).split(' ').map(function (value) {
    return parseInt(value);
  });
};

let array = readline().getNumArray(),
    n = array[0],
    m = array[1],
    empty = '.',
    filled = '#',
    snake = [];

for (let i = 0; i < n; i++) {
  let str = '';
  for (let j = 0; j < m; j++) {
    if (i % 2 === 0) {
      str += filled;
    } else {
      if (j === m - 1) {
        str += filled;
      } else {
        str += empty;
      }
    }
  }
  snake.push(str);
}
for (let i = 0; i < snake.length; i++){
  write(snake[i]);
};

var inputs = readline().split(" ");
var n = inputs[0]
var m = inputs[1]
var r = 1;
var str = "";
for (var i = 0; i < m; i++) {
  for (var j = 0; j < n; j++) {
      if (i%2 == 0)
          str += "#";
      else {
          if (r==1) {
              if (j!=n-1)
                  str += ".";
              else
                  str += "#";
          }
          else if (r == 0) {
              if (j!=0)
                  str += ".";
              else
                  str += "#";
          }
      }
  }
  if (i%2 != 0) {
      if (r==1) r = 0;
      else r = 1;
  }
  print(str)
}

var params = readline().split(" ").map(value => +value);
var n = params[0], m = params[1];
var full = first = last = "";

for(var i = 0; i < n; i++) {full += "#";}
first += "#";  for(var i = 0; i < n - 1; i++) {first += ".";}
for(var i = 0; i < n - 1; i++) {last += ".";} last += "#";

for(var i = 0; i < n; i++) {
	if ((i + 1) % 2 === 1)
		print(full);
	else if ((i + 1) % 4 === 0)
		print(first);
	else
		print(last);
}

const readline = require('readline');

let secondLine = false;

// Create readline Interface
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

let inputs = [];

rl.on('line', lineInput => {
    inputs.push(lineInput);
})

// Read Inputs
rl.on('close', () => {
    const line1 = inputs[0].split(' ');
    const rows = parseInt(line1[0]);
    const cols = parseInt(line1[1]);
    let snake = '';
    let turning = false;
    let opposite = false;

    for (let i = 0; i < rows; i++) {
        for (let j = 0; j < cols; j++) {

            if (!turning) {
                snake += '#';
            } else {
                if (!opposite) {
                    if (j === cols - 1)
                        snake += '#';
                    else
                        snake += '.';
                } else {
                    if (j === 0)
                        snake += '#';
                    else
                        snake += '.';
                }
            }

        }

        if ((i + 1) % 3 === 0)
            opposite = !opposite;
        turning = !turning;
        console.log(snake);
        snake = ''
    }

});

let fs = require('fs');

let txt = fs.readFileSync(0, "utf-8").split(/[\n\r]/).filter(data => data.length > 0);

for (let i = 0; i < txt.length; i++) {
    let info = txt[i].split(" ");
    doit(info[0] * 1, info[1] * 1);
}

function doit(n, n1) {
    let drawing = "";
    for (let i = 1; i <= n; i++) {
        if (i % 2 == 1) {
            if (n != 1) {
                drawing = drawing.concat("\n");
                drawing = drawing.concat(new Array(n1).fill("#").join(""));
            } else {
                drawing = drawing.concat(new Array(n1).fill("#").join(""));
            }
        } else {
            drawing = drawing.concat("\n");
            if (i % 4 == 2) {
                drawing = drawing.concat(new Array(n1 - 1).fill(".").join(""));
                drawing = drawing.concat("#");
            } else {
                drawing = drawing.concat("#");
                drawing = drawing.concat(new Array(n1 - 1).fill(".").join(""));
            }
        }

    }
    console.log(drawing);

}