import random failed def check if or return False if return False if r

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import random
failed = [
(2, 2),
(3, 3),
(2, 3),
(3, 2),
(2, 4),
(4, 2)
]
def check(u, v):
if u[0] == v[0] or u[1] == v[1]:
return False
if u[0] - u[1] == v[0] - v[1]:
return False
if u[0] + u[1] == v[0] + v[1]:
return False
return True
def process(d):
for i in range(len(d)-1):
if not check(d[i], d[i+1]):
for j in range(i+2, len(d)):
if check(d[i], d[j]):
d[i+1], d[j] = d[j], d[i+1]
break
if not check(d[i], d[i+1]):
return False
return True
t = int(input())
for test_num in range(1, t + 1):
n, m = map(int, input().split(' '))
if (n, m) in failed:
print("Case #{}: IMPOSSIBLE".format(test_num))
continue
r = [(i+1, j+1) for i in range(n) for j in range(m)]
while True:
random.shuffle(r)
if process(r):
print("Case #{}: POSSIBLE".format(test_num))
for step in r:
print('{} {}'.format(step[0], step[1]))
break