message stringlengths 2 19.9k | message_type stringclasses 2
values | message_id int64 0 1 | conversation_id int64 322 108k | cluster float64 15 15 | __index_level_0__ int64 644 217k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
You are standing on the OX-axis at point 0 and you want to move to an integer point x > 0.
You can make several jumps. Suppose you're currently at point y (y may be negative) and jump for the k-th time. You can:
* either jump to the point y + k
* or jump to the point y - 1.
What is the minimum number of jumps you need to reach the point x?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases.
The first and only line of each test case contains the single integer x (1 β€ x β€ 10^6) β the destination point.
Output
For each test case, print the single integer β the minimum number of jumps to reach x. It can be proved that we can reach any integer point x.
Example
Input
5
1
2
3
4
5
Output
1
3
2
3
4
Note
In the first test case x = 1, so you need only one jump: the 1-st jump from 0 to 0 + 1 = 1.
In the second test case x = 2. You need at least three jumps:
* the 1-st jump from 0 to 0 + 1 = 1;
* the 2-nd jump from 1 to 1 + 2 = 3;
* the 3-rd jump from 3 to 3 - 1 = 2;
Two jumps are not enough because these are the only possible variants:
* the 1-st jump as -1 and the 2-nd one as -1 β you'll reach 0 -1 -1 =-2;
* the 1-st jump as -1 and the 2-nd one as +2 β you'll reach 0 -1 +2 = 1;
* the 1-st jump as +1 and the 2-nd one as -1 β you'll reach 0 +1 -1 = 0;
* the 1-st jump as +1 and the 2-nd one as +2 β you'll reach 0 +1 +2 = 3;
In the third test case, you need two jumps: the 1-st one as +1 and the 2-nd one as +2, so 0 + 1 + 2 = 3.
In the fourth test case, you need three jumps: the 1-st one as -1, the 2-nd one as +2 and the 3-rd one as +3, so 0 - 1 + 2 + 3 = 4. | instruction | 0 | 71,858 | 15 | 143,716 |
Tags: constructive algorithms, math
Correct Solution:
```
# Competitive Programming Template --> Ankit Josh
import os
from math import factorial
import sys
from io import BytesIO, IOBase
def inp(): return sys.stdin.readline().strip()
def IIX(): return (int(x) for x in sys.stdin.readline().split())
def II(): return (int(inp()))
def LI(): return list(map(int, inp().split()))
def LS(): return list(map(str, inp().split()))
def L(x):return list(x)
def out(var): return sys.stdout.write(str(var))
#Graph using Ajdacency List
class GraphAL:
def __init__(self,Nodes,isDirected=False):
self.nodes=[x for x in range(1,Nodes+1) ]
self.adj_list={}
self.isDirected=isDirected
for node in self.nodes:
self.adj_list[node]=[]
def add_edge(self,x,y):
self.adj_list[x].append(y)
if self.isDirected==False:
self.adj_list[y].append(x)
def return_graph(self):
return(self.adj_list)
#Graph using Ajdacency Matrix
class GraphAM:
def __init__(self,Nodes,isDirected=False):
self.adj_matrix=[ [0]*(Nodes+1) for x in range(Nodes+2)]
self.isDirected=isDirected
def add_edge(self,x,y):
if self.isDirected:
self.adj_matrix[x][y]=1
elif self.isDirected==False:
self.adj_matrix[x][y]=1
self.adj_matrix[y][x]=1
def delete_edge(self,x,y):
if self.isDirected:
self.adj_matrix[x][y]=0
if self.isDirected==False:
self.adj_matrix[x][y]=0
self.adj_matrix[y][x]=0
def degree(self,x):
l=self.adj_matrix[x]
return l.count(1)
def return_graph(self):
return self.adj_matrix
'''
nodes=II()
edges=II()
graph=GraphAL(nodes) #Add 'True' to the Graph method, for directed graph
connections=[]
for i in range(edges):
l=LI()
connections.append(l)
for connect in connections:
graph.add_edge(connect[0],connect[1])
grp=graph.return_graph()
'''
#Code goes here
def solve():
#Start coding
x=II()
y, q1 = 0, 0
while y < x:
q1 += 1
y += q1
print(q1+(x == y-1))
#lst=[(x*(x+1)//2) for x in range(n+1)]
#[0, 1, 3, 6, 10, 15, 21, 28, 36, 45]
#lst[min(range(len(lst)), key = lambda i: abs(lst[i]-10))]
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
try:
t=II()
for _ in range(t):
solve()
except EOFError as e:
out('')
except RuntimeError as r:
out('')
``` | output | 1 | 71,858 | 15 | 143,717 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are standing on the OX-axis at point 0 and you want to move to an integer point x > 0.
You can make several jumps. Suppose you're currently at point y (y may be negative) and jump for the k-th time. You can:
* either jump to the point y + k
* or jump to the point y - 1.
What is the minimum number of jumps you need to reach the point x?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases.
The first and only line of each test case contains the single integer x (1 β€ x β€ 10^6) β the destination point.
Output
For each test case, print the single integer β the minimum number of jumps to reach x. It can be proved that we can reach any integer point x.
Example
Input
5
1
2
3
4
5
Output
1
3
2
3
4
Note
In the first test case x = 1, so you need only one jump: the 1-st jump from 0 to 0 + 1 = 1.
In the second test case x = 2. You need at least three jumps:
* the 1-st jump from 0 to 0 + 1 = 1;
* the 2-nd jump from 1 to 1 + 2 = 3;
* the 3-rd jump from 3 to 3 - 1 = 2;
Two jumps are not enough because these are the only possible variants:
* the 1-st jump as -1 and the 2-nd one as -1 β you'll reach 0 -1 -1 =-2;
* the 1-st jump as -1 and the 2-nd one as +2 β you'll reach 0 -1 +2 = 1;
* the 1-st jump as +1 and the 2-nd one as -1 β you'll reach 0 +1 -1 = 0;
* the 1-st jump as +1 and the 2-nd one as +2 β you'll reach 0 +1 +2 = 3;
In the third test case, you need two jumps: the 1-st one as +1 and the 2-nd one as +2, so 0 + 1 + 2 = 3.
In the fourth test case, you need three jumps: the 1-st one as -1, the 2-nd one as +2 and the 3-rd one as +3, so 0 - 1 + 2 + 3 = 4. | instruction | 0 | 71,859 | 15 | 143,718 |
Tags: constructive algorithms, math
Correct Solution:
```
for _ in range(int(input()) if True else 1):
n=(int)(input())
c=0
for i in range(1,n+1):
if (i*(i+1))//2>=n:
c=i
v=(i*(i+1))//2
break
if (v-n==1):
print(c+1)
else:
print(c)
``` | output | 1 | 71,859 | 15 | 143,719 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are standing on the OX-axis at point 0 and you want to move to an integer point x > 0.
You can make several jumps. Suppose you're currently at point y (y may be negative) and jump for the k-th time. You can:
* either jump to the point y + k
* or jump to the point y - 1.
What is the minimum number of jumps you need to reach the point x?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases.
The first and only line of each test case contains the single integer x (1 β€ x β€ 10^6) β the destination point.
Output
For each test case, print the single integer β the minimum number of jumps to reach x. It can be proved that we can reach any integer point x.
Example
Input
5
1
2
3
4
5
Output
1
3
2
3
4
Note
In the first test case x = 1, so you need only one jump: the 1-st jump from 0 to 0 + 1 = 1.
In the second test case x = 2. You need at least three jumps:
* the 1-st jump from 0 to 0 + 1 = 1;
* the 2-nd jump from 1 to 1 + 2 = 3;
* the 3-rd jump from 3 to 3 - 1 = 2;
Two jumps are not enough because these are the only possible variants:
* the 1-st jump as -1 and the 2-nd one as -1 β you'll reach 0 -1 -1 =-2;
* the 1-st jump as -1 and the 2-nd one as +2 β you'll reach 0 -1 +2 = 1;
* the 1-st jump as +1 and the 2-nd one as -1 β you'll reach 0 +1 -1 = 0;
* the 1-st jump as +1 and the 2-nd one as +2 β you'll reach 0 +1 +2 = 3;
In the third test case, you need two jumps: the 1-st one as +1 and the 2-nd one as +2, so 0 + 1 + 2 = 3.
In the fourth test case, you need three jumps: the 1-st one as -1, the 2-nd one as +2 and the 3-rd one as +3, so 0 - 1 + 2 + 3 = 4. | instruction | 0 | 71,860 | 15 | 143,720 |
Tags: constructive algorithms, math
Correct Solution:
```
from math import ceil
t=int(input())
for _ in range(t):
n=int(input())
count=0
now=0
if(n==2):
print(3)
continue
for i in range(1,n+1):
count+=1
now+=i
if(now>=n):
break
if(now!=n and now-1==n):
print(count+1)
else:
print(count)
``` | output | 1 | 71,860 | 15 | 143,721 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are standing on the OX-axis at point 0 and you want to move to an integer point x > 0.
You can make several jumps. Suppose you're currently at point y (y may be negative) and jump for the k-th time. You can:
* either jump to the point y + k
* or jump to the point y - 1.
What is the minimum number of jumps you need to reach the point x?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases.
The first and only line of each test case contains the single integer x (1 β€ x β€ 10^6) β the destination point.
Output
For each test case, print the single integer β the minimum number of jumps to reach x. It can be proved that we can reach any integer point x.
Example
Input
5
1
2
3
4
5
Output
1
3
2
3
4
Note
In the first test case x = 1, so you need only one jump: the 1-st jump from 0 to 0 + 1 = 1.
In the second test case x = 2. You need at least three jumps:
* the 1-st jump from 0 to 0 + 1 = 1;
* the 2-nd jump from 1 to 1 + 2 = 3;
* the 3-rd jump from 3 to 3 - 1 = 2;
Two jumps are not enough because these are the only possible variants:
* the 1-st jump as -1 and the 2-nd one as -1 β you'll reach 0 -1 -1 =-2;
* the 1-st jump as -1 and the 2-nd one as +2 β you'll reach 0 -1 +2 = 1;
* the 1-st jump as +1 and the 2-nd one as -1 β you'll reach 0 +1 -1 = 0;
* the 1-st jump as +1 and the 2-nd one as +2 β you'll reach 0 +1 +2 = 3;
In the third test case, you need two jumps: the 1-st one as +1 and the 2-nd one as +2, so 0 + 1 + 2 = 3.
In the fourth test case, you need three jumps: the 1-st one as -1, the 2-nd one as +2 and the 3-rd one as +3, so 0 - 1 + 2 + 3 = 4. | instruction | 0 | 71,861 | 15 | 143,722 |
Tags: constructive algorithms, math
Correct Solution:
```
t = int(input())
for _ in range(t):
x = int(input())
for i in range(1, x + 1):
if i * (i + 1) >= 2 * x:
break
k = (i * (i + 1)) // 2
print(i + 1 if k == x + 1 else i)
``` | output | 1 | 71,861 | 15 | 143,723 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won.
Alex has grown up since then, so he easily wins the most difficult levels. This quickly bored him, and he thought: what if the computer gave him invalid fields in the childhood and Alex could not win because of it?
He needs your help to check it.
A Minesweeper field is a rectangle n Γ m, where each cell is either empty, or contains a digit from 1 to 8, or a bomb. The field is valid if for each cell:
* if there is a digit k in the cell, then exactly k neighboring cells have bombs.
* if the cell is empty, then all neighboring cells have no bombs.
Two cells are neighbors if they have a common side or a corner (i. e. a cell has at most 8 neighboring cells).
Input
The first line contains two integers n and m (1 β€ n, m β€ 100) β the sizes of the field.
The next n lines contain the description of the field. Each line contains m characters, each of them is "." (if this cell is empty), "*" (if there is bomb in this cell), or a digit from 1 to 8, inclusive.
Output
Print "YES", if the field is valid and "NO" otherwise.
You can choose the case (lower or upper) for each letter arbitrarily.
Examples
Input
3 3
111
1*1
111
Output
YES
Input
2 4
*.*.
1211
Output
NO
Note
In the second example the answer is "NO" because, if the positions of the bombs are preserved, the first line of the field should be *2*1.
You can read more about Minesweeper in Wikipedia's article. | instruction | 0 | 72,252 | 15 | 144,504 |
Tags: implementation
Correct Solution:
```
r, c = map(int, input().split())
b = [list(input()) for i in range(r)]
for y in range(r):
for x in range(c):
if b[y][x] == '.':
b[y][x] = '0'
ok = True
for Y in range(r):
for X in range(c):
if not b[Y][X].isdigit():
continue
p = 0
for dy in range(-1, 2):
for dx in range(-1, 2):
y = Y + dy
x = X + dx
if 0 <= y < r and 0 <= x < c:
p += b[y][x] == '*'
if p != int(b[Y][X]):
ok = False
print(["NO", "YES"][ok])
``` | output | 1 | 72,252 | 15 | 144,505 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won.
Alex has grown up since then, so he easily wins the most difficult levels. This quickly bored him, and he thought: what if the computer gave him invalid fields in the childhood and Alex could not win because of it?
He needs your help to check it.
A Minesweeper field is a rectangle n Γ m, where each cell is either empty, or contains a digit from 1 to 8, or a bomb. The field is valid if for each cell:
* if there is a digit k in the cell, then exactly k neighboring cells have bombs.
* if the cell is empty, then all neighboring cells have no bombs.
Two cells are neighbors if they have a common side or a corner (i. e. a cell has at most 8 neighboring cells).
Input
The first line contains two integers n and m (1 β€ n, m β€ 100) β the sizes of the field.
The next n lines contain the description of the field. Each line contains m characters, each of them is "." (if this cell is empty), "*" (if there is bomb in this cell), or a digit from 1 to 8, inclusive.
Output
Print "YES", if the field is valid and "NO" otherwise.
You can choose the case (lower or upper) for each letter arbitrarily.
Examples
Input
3 3
111
1*1
111
Output
YES
Input
2 4
*.*.
1211
Output
NO
Note
In the second example the answer is "NO" because, if the positions of the bombs are preserved, the first line of the field should be *2*1.
You can read more about Minesweeper in Wikipedia's article. | instruction | 0 | 72,253 | 15 | 144,506 |
Tags: implementation
Correct Solution:
```
def cntBomb(i,j):
global n,m,x
cnt=0
if x[i-1][j]=='*': cnt+=1
if x[i+1][j]=='*': cnt+=1
if x[i][j-1]=='*': cnt+=1
if x[i][j+1]=='*': cnt+=1
if x[i-1][j-1]=='*': cnt+=1
if x[i-1][j+1]=='*': cnt+=1
if x[i+1][j-1]=='*': cnt+=1
if x[i+1][j+1]=='*': cnt+=1
return cnt
n,m=map(int,input().split())
x=[0]*(n+2)
x[0]=['.']*(m+2)
x[-1]=['.']*(m+2)
for i in range(1,n+1):
x[i]=['.']
x[i].extend(list(input()))
x[i].append('.')
for i in range(1,n+1):
for j in range(1,m+1):
c=x[i][j]
if ord('1')<=ord(c)<=ord('8') or c=='.':
if c=='.': c=0
if cntBomb(i,j) != int(c):
print('NO')
exit()
print('YES')
``` | output | 1 | 72,253 | 15 | 144,507 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won.
Alex has grown up since then, so he easily wins the most difficult levels. This quickly bored him, and he thought: what if the computer gave him invalid fields in the childhood and Alex could not win because of it?
He needs your help to check it.
A Minesweeper field is a rectangle n Γ m, where each cell is either empty, or contains a digit from 1 to 8, or a bomb. The field is valid if for each cell:
* if there is a digit k in the cell, then exactly k neighboring cells have bombs.
* if the cell is empty, then all neighboring cells have no bombs.
Two cells are neighbors if they have a common side or a corner (i. e. a cell has at most 8 neighboring cells).
Input
The first line contains two integers n and m (1 β€ n, m β€ 100) β the sizes of the field.
The next n lines contain the description of the field. Each line contains m characters, each of them is "." (if this cell is empty), "*" (if there is bomb in this cell), or a digit from 1 to 8, inclusive.
Output
Print "YES", if the field is valid and "NO" otherwise.
You can choose the case (lower or upper) for each letter arbitrarily.
Examples
Input
3 3
111
1*1
111
Output
YES
Input
2 4
*.*.
1211
Output
NO
Note
In the second example the answer is "NO" because, if the positions of the bombs are preserved, the first line of the field should be *2*1.
You can read more about Minesweeper in Wikipedia's article. | instruction | 0 | 72,254 | 15 | 144,508 |
Tags: implementation
Correct Solution:
```
n,m=map(int,input().split())
dx=[0,0,-1,1,-1,-1,1,1]
dy=[-1,1,0,0,-1,1,-1,1]
g=[]
for _ in range(n):
g.append(input())
for i in range(n):
for j in range(m):
c=g[i][j]
if c=='*':
continue
d=0
if c>='1' and c<='9':
d=int(c)
s=0
for k in range(8):
x=i+dx[k]
y=j+dy[k]
if x>=0 and y>=0 and x<n and y<m:
if g[x][y]=='*':
s+=1
if s!=d:
print('NO')
exit()
print('YES')
``` | output | 1 | 72,254 | 15 | 144,509 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won.
Alex has grown up since then, so he easily wins the most difficult levels. This quickly bored him, and he thought: what if the computer gave him invalid fields in the childhood and Alex could not win because of it?
He needs your help to check it.
A Minesweeper field is a rectangle n Γ m, where each cell is either empty, or contains a digit from 1 to 8, or a bomb. The field is valid if for each cell:
* if there is a digit k in the cell, then exactly k neighboring cells have bombs.
* if the cell is empty, then all neighboring cells have no bombs.
Two cells are neighbors if they have a common side or a corner (i. e. a cell has at most 8 neighboring cells).
Input
The first line contains two integers n and m (1 β€ n, m β€ 100) β the sizes of the field.
The next n lines contain the description of the field. Each line contains m characters, each of them is "." (if this cell is empty), "*" (if there is bomb in this cell), or a digit from 1 to 8, inclusive.
Output
Print "YES", if the field is valid and "NO" otherwise.
You can choose the case (lower or upper) for each letter arbitrarily.
Examples
Input
3 3
111
1*1
111
Output
YES
Input
2 4
*.*.
1211
Output
NO
Note
In the second example the answer is "NO" because, if the positions of the bombs are preserved, the first line of the field should be *2*1.
You can read more about Minesweeper in Wikipedia's article. | instruction | 0 | 72,255 | 15 | 144,510 |
Tags: implementation
Correct Solution:
```
from sys import stdin
n, m = map(int, stdin.readline().strip().split())
field = []
for i in range(n):
field.append(stdin.readline().strip())
def neighboring_bombs(field, n, m, i, j):
count = 0
for ii in range(max(i - 1, 0), min(i + 2, n)):
for jj in range(max(j - 1, 0), min(j + 2, m)):
if ii == i and jj == j:
continue
if field[ii][jj] == '*':
count += 1
return count
def valid(field, n, m):
for i in range(n):
for j in range(m):
if field[i][j] == '*':
continue
if field[i][j] == '.':
expect_bombs = 0
else:
expect_bombs = ord(field[i][j]) - ord('0')
actual_bombs = neighboring_bombs(field, n, m, i, j)
if actual_bombs != expect_bombs:
return False
return True
if valid(field, n, m):
print('YES')
else:
print('NO')
``` | output | 1 | 72,255 | 15 | 144,511 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won.
Alex has grown up since then, so he easily wins the most difficult levels. This quickly bored him, and he thought: what if the computer gave him invalid fields in the childhood and Alex could not win because of it?
He needs your help to check it.
A Minesweeper field is a rectangle n Γ m, where each cell is either empty, or contains a digit from 1 to 8, or a bomb. The field is valid if for each cell:
* if there is a digit k in the cell, then exactly k neighboring cells have bombs.
* if the cell is empty, then all neighboring cells have no bombs.
Two cells are neighbors if they have a common side or a corner (i. e. a cell has at most 8 neighboring cells).
Input
The first line contains two integers n and m (1 β€ n, m β€ 100) β the sizes of the field.
The next n lines contain the description of the field. Each line contains m characters, each of them is "." (if this cell is empty), "*" (if there is bomb in this cell), or a digit from 1 to 8, inclusive.
Output
Print "YES", if the field is valid and "NO" otherwise.
You can choose the case (lower or upper) for each letter arbitrarily.
Examples
Input
3 3
111
1*1
111
Output
YES
Input
2 4
*.*.
1211
Output
NO
Note
In the second example the answer is "NO" because, if the positions of the bombs are preserved, the first line of the field should be *2*1.
You can read more about Minesweeper in Wikipedia's article. | instruction | 0 | 72,256 | 15 | 144,512 |
Tags: implementation
Correct Solution:
```
n, m = map(int, input().split())
a = [input() for _ in range(n)]
ans = 'YES'
for i in range(n):
for j in range(m):
if a[i][j] != '*':
s = sum(0<=k<n and 0<=l<m and a[k][l] == '*'
for k in range(i-1, i+2) for l in range(j-1, j+2))
if str(s or '.') != a[i][j]:
ans = 'NO'
break
else:
continue
break
print(ans)
``` | output | 1 | 72,256 | 15 | 144,513 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won.
Alex has grown up since then, so he easily wins the most difficult levels. This quickly bored him, and he thought: what if the computer gave him invalid fields in the childhood and Alex could not win because of it?
He needs your help to check it.
A Minesweeper field is a rectangle n Γ m, where each cell is either empty, or contains a digit from 1 to 8, or a bomb. The field is valid if for each cell:
* if there is a digit k in the cell, then exactly k neighboring cells have bombs.
* if the cell is empty, then all neighboring cells have no bombs.
Two cells are neighbors if they have a common side or a corner (i. e. a cell has at most 8 neighboring cells).
Input
The first line contains two integers n and m (1 β€ n, m β€ 100) β the sizes of the field.
The next n lines contain the description of the field. Each line contains m characters, each of them is "." (if this cell is empty), "*" (if there is bomb in this cell), or a digit from 1 to 8, inclusive.
Output
Print "YES", if the field is valid and "NO" otherwise.
You can choose the case (lower or upper) for each letter arbitrarily.
Examples
Input
3 3
111
1*1
111
Output
YES
Input
2 4
*.*.
1211
Output
NO
Note
In the second example the answer is "NO" because, if the positions of the bombs are preserved, the first line of the field should be *2*1.
You can read more about Minesweeper in Wikipedia's article. | instruction | 0 | 72,257 | 15 | 144,514 |
Tags: implementation
Correct Solution:
```
#!/usr/bin/env python3
from sys import stdin, stdout
def rint():
return map(int, stdin.readline().split())
#lines = stdin.readlines()
r, c = rint()
def check (i, j):
cur_val = m[i][j]
if cur_val == -1:
return True
cnt = 0
p = [[-1, -1, -1] for _ in range(3)]
p[1][1] = 0
if i-1 < 0:
p[0][0] = 0
p[0][1] = 0
p[0][2] = 0
if j-1 < 0:
p[0][0] = 0
p[1][0] = 0
p[2][0] = 0
if i+1 >= r:
p[2][0] = 0
p[2][1] = 0
p[2][2] = 0
if j+1 >= c:
p[0][2] = 0
p[1][2] = 0
p[2][2] = 0
for rr in range(3):
for cc in range(3):
if p[rr][cc] == 0:
continue
if m[i+rr-1][j+cc-1] == -1:
cnt += 1
return cnt == m[i][j]
m = []
for i in range(r):
tmp = input()
tmp2 = []
for i in range(c):
if tmp[i] == '.':
tmp2.append(0)
elif tmp[i] == '*':
tmp2.append(-1)
else:
tmp2.append(int(tmp[i]))
m.append(tmp2)
for i in range(r):
for j in range(c):
if check(i,j) == False:
print("NO")
exit()
print("YES")
``` | output | 1 | 72,257 | 15 | 144,515 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won.
Alex has grown up since then, so he easily wins the most difficult levels. This quickly bored him, and he thought: what if the computer gave him invalid fields in the childhood and Alex could not win because of it?
He needs your help to check it.
A Minesweeper field is a rectangle n Γ m, where each cell is either empty, or contains a digit from 1 to 8, or a bomb. The field is valid if for each cell:
* if there is a digit k in the cell, then exactly k neighboring cells have bombs.
* if the cell is empty, then all neighboring cells have no bombs.
Two cells are neighbors if they have a common side or a corner (i. e. a cell has at most 8 neighboring cells).
Input
The first line contains two integers n and m (1 β€ n, m β€ 100) β the sizes of the field.
The next n lines contain the description of the field. Each line contains m characters, each of them is "." (if this cell is empty), "*" (if there is bomb in this cell), or a digit from 1 to 8, inclusive.
Output
Print "YES", if the field is valid and "NO" otherwise.
You can choose the case (lower or upper) for each letter arbitrarily.
Examples
Input
3 3
111
1*1
111
Output
YES
Input
2 4
*.*.
1211
Output
NO
Note
In the second example the answer is "NO" because, if the positions of the bombs are preserved, the first line of the field should be *2*1.
You can read more about Minesweeper in Wikipedia's article. | instruction | 0 | 72,258 | 15 | 144,516 |
Tags: implementation
Correct Solution:
```
def bad_num(k):
tb = 0
for x in [-1, 0, 1]:
for y in [-1, 0, 1]:
if pole[i+x][j+y] == '*':
tb +=1
return tb == k
n, m = list(map(int, input().split()))
pole = []
for i in range(n):
arr = list(input().strip())
arr.append('.')
pole.append(arr)
pole.append('.'*(m+1))
for i in range(n):
for j in range(m):
cur = pole[i][j]
if cur == '.':
cur = '0'
if cur in '0123456789':
if bad_num(int(cur)):
continue
else:
print('NO')
exit()
elif cur != '*':
print('NO')
exit()
print('YES')
``` | output | 1 | 72,258 | 15 | 144,517 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won.
Alex has grown up since then, so he easily wins the most difficult levels. This quickly bored him, and he thought: what if the computer gave him invalid fields in the childhood and Alex could not win because of it?
He needs your help to check it.
A Minesweeper field is a rectangle n Γ m, where each cell is either empty, or contains a digit from 1 to 8, or a bomb. The field is valid if for each cell:
* if there is a digit k in the cell, then exactly k neighboring cells have bombs.
* if the cell is empty, then all neighboring cells have no bombs.
Two cells are neighbors if they have a common side or a corner (i. e. a cell has at most 8 neighboring cells).
Input
The first line contains two integers n and m (1 β€ n, m β€ 100) β the sizes of the field.
The next n lines contain the description of the field. Each line contains m characters, each of them is "." (if this cell is empty), "*" (if there is bomb in this cell), or a digit from 1 to 8, inclusive.
Output
Print "YES", if the field is valid and "NO" otherwise.
You can choose the case (lower or upper) for each letter arbitrarily.
Examples
Input
3 3
111
1*1
111
Output
YES
Input
2 4
*.*.
1211
Output
NO
Note
In the second example the answer is "NO" because, if the positions of the bombs are preserved, the first line of the field should be *2*1.
You can read more about Minesweeper in Wikipedia's article. | instruction | 0 | 72,259 | 15 | 144,518 |
Tags: implementation
Correct Solution:
```
n,m = map(int,input().split())
a =[]
for i in range(n):
a.append(input())
f = 1
for i in range(n):
for j in range(m):
c = 0
if a[i][j] == '.':t=0
elif a[i][j] == '*':t=-1
else:t=int(a[i][j])
if t!= -1:
for k1 in range(-1,2):
for k2 in range(-1,2):
if (0 <= i+k1 < n)and(0 <= j+k2 <m):
if a[i+k1][j+k2] == '*':c+=1
if c!=t:
f = 0
break
if f:print('YES')
else:print('NO')
``` | output | 1 | 72,259 | 15 | 144,519 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won.
Alex has grown up since then, so he easily wins the most difficult levels. This quickly bored him, and he thought: what if the computer gave him invalid fields in the childhood and Alex could not win because of it?
He needs your help to check it.
A Minesweeper field is a rectangle n Γ m, where each cell is either empty, or contains a digit from 1 to 8, or a bomb. The field is valid if for each cell:
* if there is a digit k in the cell, then exactly k neighboring cells have bombs.
* if the cell is empty, then all neighboring cells have no bombs.
Two cells are neighbors if they have a common side or a corner (i. e. a cell has at most 8 neighboring cells).
Input
The first line contains two integers n and m (1 β€ n, m β€ 100) β the sizes of the field.
The next n lines contain the description of the field. Each line contains m characters, each of them is "." (if this cell is empty), "*" (if there is bomb in this cell), or a digit from 1 to 8, inclusive.
Output
Print "YES", if the field is valid and "NO" otherwise.
You can choose the case (lower or upper) for each letter arbitrarily.
Examples
Input
3 3
111
1*1
111
Output
YES
Input
2 4
*.*.
1211
Output
NO
Note
In the second example the answer is "NO" because, if the positions of the bombs are preserved, the first line of the field should be *2*1.
You can read more about Minesweeper in Wikipedia's article.
Submitted Solution:
```
arr = []
def valid(i, j):
bombs = 0
if arr[i][j] == '*':
return True
if i != len(arr) - 1:
if arr[i + 1][j] == '*':
bombs += 1
if i != 0:
if arr[i - 1][j] == '*':
bombs += 1
if j != len(arr[0]) - 1:
if arr[i][j + 1] == '*':
bombs += 1
if j != 0:
if arr[i][j - 1] == '*':
bombs += 1
if i != 0 and j != 0:
if arr[i-1][j - 1] == '*':
bombs += 1
if i != 0 and j != len(arr[0]) - 1:
if arr[i-1][j + 1] == '*':
bombs += 1
if i != len(arr) - 1 and j != 0:
if arr[i+1][j - 1] == '*':
bombs += 1
if i != len(arr) - 1 and j != len(arr[0]) - 1:
if arr[i+1][j + 1] == '*':
bombs += 1
if bombs == 0 and (arr[i][j] == '.'):
return True
if arr[i][j] == '.':
return False
if int(arr[i][j]) == bombs:
return True
return False
n, m = list(map(int, input().split()))
for i in range(n):
line = input()
arr2 = []
for j in range(m):
arr2.append(line[j:j+1])
arr.append(arr2)
ans = "YES"
for i in range(n):
for j in range(m):
if not valid(i, j):
ans = "NO"
print(ans)
``` | instruction | 0 | 72,260 | 15 | 144,520 |
Yes | output | 1 | 72,260 | 15 | 144,521 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won.
Alex has grown up since then, so he easily wins the most difficult levels. This quickly bored him, and he thought: what if the computer gave him invalid fields in the childhood and Alex could not win because of it?
He needs your help to check it.
A Minesweeper field is a rectangle n Γ m, where each cell is either empty, or contains a digit from 1 to 8, or a bomb. The field is valid if for each cell:
* if there is a digit k in the cell, then exactly k neighboring cells have bombs.
* if the cell is empty, then all neighboring cells have no bombs.
Two cells are neighbors if they have a common side or a corner (i. e. a cell has at most 8 neighboring cells).
Input
The first line contains two integers n and m (1 β€ n, m β€ 100) β the sizes of the field.
The next n lines contain the description of the field. Each line contains m characters, each of them is "." (if this cell is empty), "*" (if there is bomb in this cell), or a digit from 1 to 8, inclusive.
Output
Print "YES", if the field is valid and "NO" otherwise.
You can choose the case (lower or upper) for each letter arbitrarily.
Examples
Input
3 3
111
1*1
111
Output
YES
Input
2 4
*.*.
1211
Output
NO
Note
In the second example the answer is "NO" because, if the positions of the bombs are preserved, the first line of the field should be *2*1.
You can read more about Minesweeper in Wikipedia's article.
Submitted Solution:
```
#http://codeforces.com/problemset/problem/984/B
def main():
n,m=list(map(int,input().split()))
field=[[0]*(m+2)]
for i in range(n):
field.append(list('0'+input().replace(".", "0")+'0'))
field.append([0]*(m+2))
for i in range(1,n+1):
for j in range(1,m+1):
if field[i][j]!='*':
if int(field[i][j])==[field[i-1][j-1], field[i][j-1],field[i+1][j-1],field[i-1][j],field[i+1][j],field[i-1][j+1],field[i][j+1],field[i+1][j+1]].count('*'):
pass
else:
print("NO")
return
else:
continue
print("YES")
if __name__=='__main__':
main()
``` | instruction | 0 | 72,261 | 15 | 144,522 |
Yes | output | 1 | 72,261 | 15 | 144,523 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won.
Alex has grown up since then, so he easily wins the most difficult levels. This quickly bored him, and he thought: what if the computer gave him invalid fields in the childhood and Alex could not win because of it?
He needs your help to check it.
A Minesweeper field is a rectangle n Γ m, where each cell is either empty, or contains a digit from 1 to 8, or a bomb. The field is valid if for each cell:
* if there is a digit k in the cell, then exactly k neighboring cells have bombs.
* if the cell is empty, then all neighboring cells have no bombs.
Two cells are neighbors if they have a common side or a corner (i. e. a cell has at most 8 neighboring cells).
Input
The first line contains two integers n and m (1 β€ n, m β€ 100) β the sizes of the field.
The next n lines contain the description of the field. Each line contains m characters, each of them is "." (if this cell is empty), "*" (if there is bomb in this cell), or a digit from 1 to 8, inclusive.
Output
Print "YES", if the field is valid and "NO" otherwise.
You can choose the case (lower or upper) for each letter arbitrarily.
Examples
Input
3 3
111
1*1
111
Output
YES
Input
2 4
*.*.
1211
Output
NO
Note
In the second example the answer is "NO" because, if the positions of the bombs are preserved, the first line of the field should be *2*1.
You can read more about Minesweeper in Wikipedia's article.
Submitted Solution:
```
n,m = map(int, input().split())
bando = list()
for i in range(n):
tmp = input()
bando.append(tmp)
def kiemtra(i,j):
bom=0
toado=[[i-1,j-1],[i-1,j],[i-1,j+1],[i,j-1],[i,j+1],[i+1,j-1],[i+1,j],[i+1,j+1]]
for tmp in toado:
if tmp[0] <0 or tmp[0]>=n or tmp[1]<0 or tmp[1]>=m:
continue
if bando[tmp[0]][tmp[1]]=='*':
bom+=1
return bom
for i in range(n):
for j in range(m):
if bando[i][j]>='0' and bando[i][j]<='9':
tmp=int(bando[i][j])
if tmp!=kiemtra(i,j):
print('NO')
exit()
elif bando[i][j]=='.':
if kiemtra(i,j)>0:
print('NO')
exit()
print('YES')
``` | instruction | 0 | 72,262 | 15 | 144,524 |
Yes | output | 1 | 72,262 | 15 | 144,525 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won.
Alex has grown up since then, so he easily wins the most difficult levels. This quickly bored him, and he thought: what if the computer gave him invalid fields in the childhood and Alex could not win because of it?
He needs your help to check it.
A Minesweeper field is a rectangle n Γ m, where each cell is either empty, or contains a digit from 1 to 8, or a bomb. The field is valid if for each cell:
* if there is a digit k in the cell, then exactly k neighboring cells have bombs.
* if the cell is empty, then all neighboring cells have no bombs.
Two cells are neighbors if they have a common side or a corner (i. e. a cell has at most 8 neighboring cells).
Input
The first line contains two integers n and m (1 β€ n, m β€ 100) β the sizes of the field.
The next n lines contain the description of the field. Each line contains m characters, each of them is "." (if this cell is empty), "*" (if there is bomb in this cell), or a digit from 1 to 8, inclusive.
Output
Print "YES", if the field is valid and "NO" otherwise.
You can choose the case (lower or upper) for each letter arbitrarily.
Examples
Input
3 3
111
1*1
111
Output
YES
Input
2 4
*.*.
1211
Output
NO
Note
In the second example the answer is "NO" because, if the positions of the bombs are preserved, the first line of the field should be *2*1.
You can read more about Minesweeper in Wikipedia's article.
Submitted Solution:
```
n, m = map(int, input().split())
l = []
for i in range(n):
l.append(list(input()))
def isValid(n, m, i, j, l):
c = 0
if j - 1 >= 0 and l[i][j - 1] == '*':
c += 1
if j - 1 >= 0 and i - 1 >= 0 and l[i - 1][j - 1] == '*':
c += 1
if i - 1 >= 0 and l[i - 1][j] == '*':
c += 1
if j + 1 < m and i - 1 >= 0 and l[i - 1][j + 1] == '*':
c += 1
if j + 1 < m and l[i][j + 1] == '*':
c += 1
if j + 1 < m and i + 1 < n and l[i + 1][j + 1] == '*':
c += 1
if i + 1 < n and l[i + 1][j] == '*':
c += 1
if j - 1 >= 0 and i + 1 < n and l[i + 1][j - 1] == '*':
c += 1
return c == (int(l[i][j]) if l[i][j] != '.' else 0)
ok = True
for i in range(n):
for j in range(m):
if l[i][j] != '*' and not isValid(n, m, i, j, l):
ok = False
print("YES" if ok else "NO")
``` | instruction | 0 | 72,263 | 15 | 144,526 |
Yes | output | 1 | 72,263 | 15 | 144,527 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won.
Alex has grown up since then, so he easily wins the most difficult levels. This quickly bored him, and he thought: what if the computer gave him invalid fields in the childhood and Alex could not win because of it?
He needs your help to check it.
A Minesweeper field is a rectangle n Γ m, where each cell is either empty, or contains a digit from 1 to 8, or a bomb. The field is valid if for each cell:
* if there is a digit k in the cell, then exactly k neighboring cells have bombs.
* if the cell is empty, then all neighboring cells have no bombs.
Two cells are neighbors if they have a common side or a corner (i. e. a cell has at most 8 neighboring cells).
Input
The first line contains two integers n and m (1 β€ n, m β€ 100) β the sizes of the field.
The next n lines contain the description of the field. Each line contains m characters, each of them is "." (if this cell is empty), "*" (if there is bomb in this cell), or a digit from 1 to 8, inclusive.
Output
Print "YES", if the field is valid and "NO" otherwise.
You can choose the case (lower or upper) for each letter arbitrarily.
Examples
Input
3 3
111
1*1
111
Output
YES
Input
2 4
*.*.
1211
Output
NO
Note
In the second example the answer is "NO" because, if the positions of the bombs are preserved, the first line of the field should be *2*1.
You can read more about Minesweeper in Wikipedia's article.
Submitted Solution:
```
n,m=map(int,input().split())
l=[list(map(str,input())) for i in range(n)]
ch=0
for i in range(n):
for j in range(m):
if l[i][j]==".":
if j-1 >=0:
if l[i][j-1]=="*":
ch=1
print("NO")
break
if j+1<=m-1:
if l[i][j+1]=="*":
ch=1
print("NO")
break
if i-1 >=0:
if l[i-1][j]=="*":
ch=1
print("NO")
break
if i+1 <=n-1:
if l[i+1][j]=="*":
ch=1
print("NO")
break
if j-1 >=0 and i-1 >=0:
if l[i-1][j-1]=="*":
ch=1
print("NO")
break
if j-1 >=0 and i+1 <=n-1:
if l[i+1][j-1]=="*":
ch=1
print("NO")
break
if j+1 <=m-1 and i-1 >=0:
if l[i-1][j+1]=="*":
ch=1
print("NO")
break
if j+1 <=m-1 and i+1 <=n-1:
if l[i+1][j+1]=="*":
ch=1
print("NO")
break
else:
if l[i][j]!="*":
co=int(l[i][j])
#1print(co)
if j-1 >=0:
if l[i][j-1]=="*":
co-=1
if j+1<=m-1:
if l[i][j+1]=="*":
co-=1
if i-1 >=0:
if l[i-1][j]=="*":
co-=1
if i+1 <=n-1:
if l[i+1][j]=="*":
co-=1
if j-1 >=0 and i-1 >=0:
if l[i-1][j-1]=="*":
co-=1
if j-1 >=0 and i+1 <=n-1:
if l[i+1][j-1]=="*":
co-=1
if j+1 <=m-1 and i-1 >=0:
if l[i-1][j+1]=="*":
co-=1
if j+1 <=m-1 and i+1 <=n-1:
if l[i+1][j+1]=="*":
co-=1
if co<0:
ch=1
print("NO")
break
if ch:
break
if not ch:
print("YES")
``` | instruction | 0 | 72,264 | 15 | 144,528 |
No | output | 1 | 72,264 | 15 | 144,529 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won.
Alex has grown up since then, so he easily wins the most difficult levels. This quickly bored him, and he thought: what if the computer gave him invalid fields in the childhood and Alex could not win because of it?
He needs your help to check it.
A Minesweeper field is a rectangle n Γ m, where each cell is either empty, or contains a digit from 1 to 8, or a bomb. The field is valid if for each cell:
* if there is a digit k in the cell, then exactly k neighboring cells have bombs.
* if the cell is empty, then all neighboring cells have no bombs.
Two cells are neighbors if they have a common side or a corner (i. e. a cell has at most 8 neighboring cells).
Input
The first line contains two integers n and m (1 β€ n, m β€ 100) β the sizes of the field.
The next n lines contain the description of the field. Each line contains m characters, each of them is "." (if this cell is empty), "*" (if there is bomb in this cell), or a digit from 1 to 8, inclusive.
Output
Print "YES", if the field is valid and "NO" otherwise.
You can choose the case (lower or upper) for each letter arbitrarily.
Examples
Input
3 3
111
1*1
111
Output
YES
Input
2 4
*.*.
1211
Output
NO
Note
In the second example the answer is "NO" because, if the positions of the bombs are preserved, the first line of the field should be *2*1.
You can read more about Minesweeper in Wikipedia's article.
Submitted Solution:
```
n, m = map(int,input().split())
mp = []
for i in range(n):
mp.append(input())
x = 0
while x < n:
y = 0
while y < m:
# print('xx', x, y, mp[x][y])
if mp[x][y] == '*':
y += 1
continue
num = 0
for dx in range(-1, 2):
for dy in range(-1, 2):
tx = x + dx
ty = y + dy
if tx < 0 or tx >= n or ty < 0 or ty >= m:
continue
if mp[tx][ty] == '*':
# print(tx, ty, mp[tx][ty])
num += 1
if mp[x][y] == '.': mp[x] =mp[x][:y] + '0' +mp[x][y:]
# print(num,mp[x][y])
if num != int(mp[x][y]):
print('NO')
quit(0)
y += 1
x += 1
print('YES')
``` | instruction | 0 | 72,265 | 15 | 144,530 |
No | output | 1 | 72,265 | 15 | 144,531 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won.
Alex has grown up since then, so he easily wins the most difficult levels. This quickly bored him, and he thought: what if the computer gave him invalid fields in the childhood and Alex could not win because of it?
He needs your help to check it.
A Minesweeper field is a rectangle n Γ m, where each cell is either empty, or contains a digit from 1 to 8, or a bomb. The field is valid if for each cell:
* if there is a digit k in the cell, then exactly k neighboring cells have bombs.
* if the cell is empty, then all neighboring cells have no bombs.
Two cells are neighbors if they have a common side or a corner (i. e. a cell has at most 8 neighboring cells).
Input
The first line contains two integers n and m (1 β€ n, m β€ 100) β the sizes of the field.
The next n lines contain the description of the field. Each line contains m characters, each of them is "." (if this cell is empty), "*" (if there is bomb in this cell), or a digit from 1 to 8, inclusive.
Output
Print "YES", if the field is valid and "NO" otherwise.
You can choose the case (lower or upper) for each letter arbitrarily.
Examples
Input
3 3
111
1*1
111
Output
YES
Input
2 4
*.*.
1211
Output
NO
Note
In the second example the answer is "NO" because, if the positions of the bombs are preserved, the first line of the field should be *2*1.
You can read more about Minesweeper in Wikipedia's article.
Submitted Solution:
```
# minsweeper.py Codeforces 984 B
def neighbors(x, y):
for i in range(-1, 2):
for j in range(-1, 2):
if (i or j):
yield (x + i, y + j)
n, m = map(int, input().split())
arr = [input() for i in range(n)]
for i in range(n):
for j in range(m):
if arr[i][j] in ".*":
continue
cnt = 0
for x, y in neighbors(i, j):
if x in range(n) and y in range(m):
cnt += arr[x][y] == '*'
if cnt != int(arr[i][j]):
print("No")
exit()
print("yes")
``` | instruction | 0 | 72,266 | 15 | 144,532 |
No | output | 1 | 72,266 | 15 | 144,533 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won.
Alex has grown up since then, so he easily wins the most difficult levels. This quickly bored him, and he thought: what if the computer gave him invalid fields in the childhood and Alex could not win because of it?
He needs your help to check it.
A Minesweeper field is a rectangle n Γ m, where each cell is either empty, or contains a digit from 1 to 8, or a bomb. The field is valid if for each cell:
* if there is a digit k in the cell, then exactly k neighboring cells have bombs.
* if the cell is empty, then all neighboring cells have no bombs.
Two cells are neighbors if they have a common side or a corner (i. e. a cell has at most 8 neighboring cells).
Input
The first line contains two integers n and m (1 β€ n, m β€ 100) β the sizes of the field.
The next n lines contain the description of the field. Each line contains m characters, each of them is "." (if this cell is empty), "*" (if there is bomb in this cell), or a digit from 1 to 8, inclusive.
Output
Print "YES", if the field is valid and "NO" otherwise.
You can choose the case (lower or upper) for each letter arbitrarily.
Examples
Input
3 3
111
1*1
111
Output
YES
Input
2 4
*.*.
1211
Output
NO
Note
In the second example the answer is "NO" because, if the positions of the bombs are preserved, the first line of the field should be *2*1.
You can read more about Minesweeper in Wikipedia's article.
Submitted Solution:
```
n,m=input().split(' ')
n=int(n)
m=int(m)
list=[]
comp="YES"
for i in range(n):
list.append(str(input()))
#print(list)
for i in range(0,n):
for j in range(0,m):
a=list[i][j]
if(ord(a)>=48 and ord(a)<=57):
a=int(a)
count=0
for b in range(-1,2):
for c in range(-1,2):
#print(list[i+b][j+c])
if i+b>=0 and i+b<n and j+c>=0 and j+c<m:
if list[i+b][j+c]=='*':
count=count+1
if count>a:
comp="NO"
break
if comp=="NO":
break
elif(a=='.'):
for b in range(-1,2):
for c in range(-1,2):
if i+b>=0 and i+b<n and j+c>=0 and j+c<m:
if list[i+b][j+c]=='*':
comp="NO"
break
if comp=="NO":
break
print(comp)
``` | instruction | 0 | 72,267 | 15 | 144,534 |
No | output | 1 | 72,267 | 15 | 144,535 |
Provide a correct Python 3 solution for this coding contest problem.
In sliding block puzzles, we repeatedly slide pieces (blocks) to open spaces within a frame to establish a goal placement of pieces.
A puzzle creator has designed a new puzzle by combining the ideas of sliding block puzzles and mazes. The puzzle is played in a rectangular frame segmented into unit squares. Some squares are pre-occupied by obstacles. There are a number of pieces placed in the frame, one 2 Γ 2 king piece and some number of 1 Γ 1 pawn pieces. Exactly two 1 Γ 1 squares are left open. If a pawn piece is adjacent to an open square, we can slide the piece there. If a whole edge of the king piece is adjacent to two open squares, we can slide the king piece. We cannot move the obstacles. Starting from a given initial placement, the objective of the puzzle is to move the king piece to the upper-left corner of the frame.
The following figure illustrates the initial placement of the fourth dataset of the sample input.
<image>
Figure E.1: The fourth dataset of the sample input.
Your task is to write a program that computes the minimum number of moves to solve the puzzle from a given placement of pieces. Here, one move means sliding either king or pawn piece to an adjacent position.
Input
The input is a sequence of datasets. The first line of a dataset consists of two integers H and W separated by a space, where H and W are the height and the width of the frame. The following H lines, each consisting of W characters, denote the initial placement of pieces. In those H lines, 'X', 'o', '*', and '.' denote a part of the king piece, a pawn piece, an obstacle, and an open square, respectively. There are no other characters in those H lines. You may assume that 3 β€ H β€ 50 and 3 β€ W β€ 50.
A line containing two zeros separated by a space indicates the end of the input.
Output
For each dataset, output a line containing the minimum number of moves required to move the king piece to the upper-left corner. If there is no way to do so, output -1.
Example
Input
3 3
oo.
oXX
.XX
3 3
XXo
XX.
o.o
3 5
.o*XX
oooXX
oooo.
7 12
oooooooooooo
ooooo*****oo
oooooo****oo
o**ooo***ooo
o***ooooo..o
o**ooooooXXo
ooooo****XXo
5 30
oooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooo
o***************************oo
XX.ooooooooooooooooooooooooooo
XX.ooooooooooooooooooooooooooo
0 0
Output
11
0
-1
382
6807 | instruction | 0 | 72,456 | 15 | 144,912 |
"Correct Solution:
```
from collections import deque
from heapq import heappush, heappop, heapify
import sys
readline = sys.stdin.readline
write = sys.stdout.write
dd = ((-1, 0), (0, -1), (1, 0), (0, 1))
Z = [-1]*(50*50)
def calc(H, W, G, x0, y0, bx, by, S):
S[:] = Z[:H*W]
k = y0*W + x0
que = deque([k])
S[k] = 0
for i in [0, 1]:
for j in [0, 1]:
S[(by+i)*W + (bx+j)] = -2
while que:
v = que.popleft()
cost = S[v]
for w in G[v]:
if S[w] == -1:
S[w] = cost+1
que.append(w)
return S
def solve():
H, W = map(int, readline().split())
if H == W == 0:
return False
M = [[0]*W for i in range(H)]
AS = []; BS = []
for i in range(H):
s = readline().strip()
Mi = M[i]
for j, c in enumerate(s):
if c == '*':
Mi[j] = -1
elif c == 'X':
Mi[j] = 1
AS.append((j, i))
elif c == '.':
BS.append((j, i))
G = [[] for i in range(H*W)]
for y in range(H):
for x in range(W):
k = y*W + x
if M[y][x] == -1:
continue
for dx, dy in dd:
nx = x + dx; ny = y + dy
if not 0 <= nx < W or not 0 <= ny < H or M[ny][nx] == -1:
continue
G[k].append(ny*W + nx)
sx, sy = min(AS)
if sx == sy == 0:
write("0\n")
return True
(x0, y0), (x1, y1) = BS
ee = [
((-1, 0), (-1, 1)),
((0, -1), (1, -1)),
((2, 0), (2, 1)),
((0, 2), (1, 2)),
]
INF = 10**9
D = [[[INF]*4 for i in range(W)] for j in range(H)]
d1 = [0]*(H*W)
d2 = [0]*(H*W)
calc(H, W, G, x0, y0, sx, sy, d1)
calc(H, W, G, x1, y1, sx, sy, d2)
que0 = []
for i in range(4):
(dx1, dy1), (dx2, dy2) = ee[i]
x1 = sx+dx1; y1 = sy+dy1
x2 = sx+dx2; y2 = sy+dy2
if not 0 <= x1 <= x2 < W or not 0 <= y1 <= y2 < H:
continue
k1 = y1*W + x1; k2 = y2*W + x2
if d1[k1] == -1 or d2[k2] == -1:
continue
d = min(d1[k1] + d2[k2], d1[k2] + d2[k1])
que0.append((d, sx, sy, i))
D[sy][sx][i] = d
heapify(que0)
while que0:
cost0, x0, y0, t0 = heappop(que0)
if D[y0][x0][t0] < cost0:
continue
if x0 == y0 == 0:
break
(dx1, dy1), (dx2, dy2) = ee[t0]
x1 = x0 + dx1; y1 = y0 + dy1
x2 = x0 + dx2; y2 = y0 + dy2
calc(H, W, G, x1, y1, x0, y0, d1)
calc(H, W, G, x2, y2, x0, y0, d2)
for t1 in range(4):
(dx3, dy3), (dx4, dy4) = ee[t1]
x3 = x0 + dx3; y3 = y0 + dy3
x4 = x0 + dx4; y4 = y0 + dy4
if not 0 <= x3 <= x4 < W or not 0 <= y3 <= y4 < H:
continue
k3 = y3*W + x3; k4 = y4*W + x4
if d1[k3] == -1 or d2[k4] == -1:
continue
d = min(d1[k3] + d2[k4], d1[k4] + d2[k3]) + 1
dx, dy = dd[t1]
nx = x0 + dx; ny = y0 + dy
if cost0 + d < D[ny][nx][t1^2]:
D[ny][nx][t1^2] = cost0 + d
heappush(que0, (cost0 + d, nx, ny, t1^2))
res = min(D[0][0][2], D[0][0][3])
if res != INF:
write("%d\n" % res)
else:
write("-1\n")
return True
while solve():
...
``` | output | 1 | 72,456 | 15 | 144,913 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive task.
Dasha and NN like playing chess. While playing a match they decided that normal chess isn't interesting enough for them, so they invented a game described below.
There are 666 black rooks and 1 white king on the chess board of size 999 Γ 999. The white king wins if he gets checked by rook, or, in other words, if he moves onto the square which shares either a row or column with a black rook.
The sides take turns, starting with white. NN plays as a white king and on each of his turns he moves a king to one of the squares that are adjacent to his current position either by side or diagonally, or, formally, if the king was on the square (x, y), it can move to the square (nx, ny) if and only max (|nx - x|, |ny - y|) = 1 , 1 β€ nx, ny β€ 999. NN is also forbidden from moving onto the squares occupied with black rooks, however, he can move onto the same row or column as a black rook.
Dasha, however, neglects playing by the chess rules, and instead of moving rooks normally she moves one of her rooks on any space devoid of other chess pieces. It is also possible that the rook would move onto the same square it was before and the position wouldn't change. However, she can't move the rook on the same row or column with the king.
Each player makes 2000 turns, if the white king wasn't checked by a black rook during those turns, black wins.
NN doesn't like losing, but thinks the task is too difficult for him, so he asks you to write a program that will always win playing for the white king. Note that Dasha can see your king and play depending on its position.
Input
In the beginning your program will receive 667 lines from input. Each line contains two integers x and y (1 β€ x, y β€ 999) β the piece's coordinates. The first line contains the coordinates of the king and the next 666 contain the coordinates of the rooks. The first coordinate denotes the number of the row where the piece is located, the second denotes the column. It is guaranteed that initially the king isn't in check and that all pieces occupy different squares.
Output
After getting king checked, you program should terminate immediately without printing anything extra.
Interaction
To make a move with the king, output two integers x and y (1 β€ x, y β€ 999) β the square to which the king would be moved. The king cannot move onto the square already occupied by a rook. It is guaranteed that the king would always have a valid move.
After each of your turns read the rook's turn in the following format: a single line containing three integers k, x and y (1 β€ k β€ 666, 1 β€ x_i, y_i β€ 999) β the number of the rook that would move and the square it would move to. It is guaranteed that the rook wouldn't move to a square already occupied by another chess piece, but it can move onto the square where it was before the turn so that its position wouldn't change. It is guaranteed that the move does not put your king into a check. If your king got in check, all three integers would be equal to -1 and in that case your program should terminate immediately.
After printing your turn do not forget to output end of line and flush the output. Otherwise you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
Answer "0 0 0" instead of a correct answer means that you made an invalid query. Exit immediately after receiving "0 0 0" and you will see Wrong answer verdict. Otherwise you can get an arbitrary verdict because your solution will continue to read from a closed stream.
Hacks are not allowed for this problem.
Example
Input
999 999
1 1
1 2
2 1
2 2
1 3
2 3
<...>
26 13
26 14
26 15
26 16
1 700 800
2 1 2
<...>
-1 -1 -1
Output
999 998
999 997
<...>
999 26
Note
The example is trimmed. The full initial positions of the rooks in the first test are available at <https://pastebin.com/qQCTXgKP>. It is not guaranteed that they will behave as in the example.
Submitted Solution:
```
import sys
def read_nums():
return [int(x) for x in input().split()]
class Brain:
def __init__(self, king, rooks) -> None:
self._position = king
self._rooks = rooks
self._rooks_set = set(map(tuple, self._rooks))
def input_rook_move(self, rook_number, x, y):
self._rooks[rook_number] = (x, y)
self._rooks_set = set(map(tuple, self._rooks))
def get_next_move(self):
possible_moves = self._get_all_possible_moves()
best_move = None
best_score = None
for move in possible_moves:
new_pos = self._get_new_position(move)
score = self._get_score(new_pos)
if best_move is None or best_score > score:
best_move = move
best_score = score
self._position = self._get_new_position(best_move)
return best_move
def _get_all_possible_moves(self):
res = []
for dx in range(-1, 0, 1):
for dy in range(-1, 0, 1):
if dx == dy == 0:
continue
new_position = self._get_new_position((dx, dy))
if new_position is not None:
res.append((dx, dy))
return res
def _get_new_position(self, move):
new_pos = self._position[0] + move[0], self._position[1] + move[1]
if 0 <= new_pos[0] < 999 and 0 <= new_pos[1] < 999 and new_pos not in self._rooks_set:
return new_pos
def _get_score(self, new_pos):
scores = [self._score(new_pos, rook_pos) for rook_pos in self._rooks]
return sum(scores) / len(scores)
def _score(self, new_pos, rook_pos):
dist = (new_pos[0] - rook_pos[0]) ** 2 + (new_pos[1] - rook_pos[1]) ** 2
return -dist
def write_next_move(x, y):
print(x, y)
sys.stdout.flush()
def read_rooks_move():
k, x, y = read_nums()
if (k, x, y) == (-1, -1, -1):
exit(0)
if (k, x, y) == (0, 0, 0):
exit(0)
return k-1, x, y
def main():
king = read_nums()
rooks = [read_nums() for _ in range(666)]
brain = Brain(king, rooks)
while True:
next_move = brain.get_next_move()
write_next_move(*next_move)
rooks_move = read_rooks_move()
brain.input_rook_move(*rooks_move)
if __name__ == '__main__':
main()
``` | instruction | 0 | 72,531 | 15 | 145,062 |
No | output | 1 | 72,531 | 15 | 145,063 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive task.
Dasha and NN like playing chess. While playing a match they decided that normal chess isn't interesting enough for them, so they invented a game described below.
There are 666 black rooks and 1 white king on the chess board of size 999 Γ 999. The white king wins if he gets checked by rook, or, in other words, if he moves onto the square which shares either a row or column with a black rook.
The sides take turns, starting with white. NN plays as a white king and on each of his turns he moves a king to one of the squares that are adjacent to his current position either by side or diagonally, or, formally, if the king was on the square (x, y), it can move to the square (nx, ny) if and only max (|nx - x|, |ny - y|) = 1 , 1 β€ nx, ny β€ 999. NN is also forbidden from moving onto the squares occupied with black rooks, however, he can move onto the same row or column as a black rook.
Dasha, however, neglects playing by the chess rules, and instead of moving rooks normally she moves one of her rooks on any space devoid of other chess pieces. It is also possible that the rook would move onto the same square it was before and the position wouldn't change. However, she can't move the rook on the same row or column with the king.
Each player makes 2000 turns, if the white king wasn't checked by a black rook during those turns, black wins.
NN doesn't like losing, but thinks the task is too difficult for him, so he asks you to write a program that will always win playing for the white king. Note that Dasha can see your king and play depending on its position.
Input
In the beginning your program will receive 667 lines from input. Each line contains two integers x and y (1 β€ x, y β€ 999) β the piece's coordinates. The first line contains the coordinates of the king and the next 666 contain the coordinates of the rooks. The first coordinate denotes the number of the row where the piece is located, the second denotes the column. It is guaranteed that initially the king isn't in check and that all pieces occupy different squares.
Output
After getting king checked, you program should terminate immediately without printing anything extra.
Interaction
To make a move with the king, output two integers x and y (1 β€ x, y β€ 999) β the square to which the king would be moved. The king cannot move onto the square already occupied by a rook. It is guaranteed that the king would always have a valid move.
After each of your turns read the rook's turn in the following format: a single line containing three integers k, x and y (1 β€ k β€ 666, 1 β€ x_i, y_i β€ 999) β the number of the rook that would move and the square it would move to. It is guaranteed that the rook wouldn't move to a square already occupied by another chess piece, but it can move onto the square where it was before the turn so that its position wouldn't change. It is guaranteed that the move does not put your king into a check. If your king got in check, all three integers would be equal to -1 and in that case your program should terminate immediately.
After printing your turn do not forget to output end of line and flush the output. Otherwise you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
Answer "0 0 0" instead of a correct answer means that you made an invalid query. Exit immediately after receiving "0 0 0" and you will see Wrong answer verdict. Otherwise you can get an arbitrary verdict because your solution will continue to read from a closed stream.
Hacks are not allowed for this problem.
Example
Input
999 999
1 1
1 2
2 1
2 2
1 3
2 3
<...>
26 13
26 14
26 15
26 16
1 700 800
2 1 2
<...>
-1 -1 -1
Output
999 998
999 997
<...>
999 26
Note
The example is trimmed. The full initial positions of the rooks in the first test are available at <https://pastebin.com/qQCTXgKP>. It is not guaranteed that they will behave as in the example.
Submitted Solution:
```
from sys import stdout
coord = []
for t in range(666):
z = list(map(int, input().split()))
coord.append(z)
xk, yk = map(int, input().split())
b1 = b2 = b3 = b4 = 0
while True:
for x, y in coord:
if x < xk and y > yk:
b1 += 1
elif x > xk and y > yk:
b2 += 1
elif x < xk and y < yk:
b3 += 1
elif x > xk and y < yk:
b4 += 1
q = max(b1, b2, b3, b4)
if q == b1:
xk -= 1
yk += 1
if q == b2:
xk += 1
yk += 1
if q == b3:
xk -= 1
yk -= 1
if q == b4:
xk += 1
yk -= 1
print(xk, yk)
stdout.flush()
k, x, y = map(int, input().split())
if k == -1:
break
else:
coord[k-1] = [x, y]
``` | instruction | 0 | 72,532 | 15 | 145,064 |
No | output | 1 | 72,532 | 15 | 145,065 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive task.
Dasha and NN like playing chess. While playing a match they decided that normal chess isn't interesting enough for them, so they invented a game described below.
There are 666 black rooks and 1 white king on the chess board of size 999 Γ 999. The white king wins if he gets checked by rook, or, in other words, if he moves onto the square which shares either a row or column with a black rook.
The sides take turns, starting with white. NN plays as a white king and on each of his turns he moves a king to one of the squares that are adjacent to his current position either by side or diagonally, or, formally, if the king was on the square (x, y), it can move to the square (nx, ny) if and only max (|nx - x|, |ny - y|) = 1 , 1 β€ nx, ny β€ 999. NN is also forbidden from moving onto the squares occupied with black rooks, however, he can move onto the same row or column as a black rook.
Dasha, however, neglects playing by the chess rules, and instead of moving rooks normally she moves one of her rooks on any space devoid of other chess pieces. It is also possible that the rook would move onto the same square it was before and the position wouldn't change. However, she can't move the rook on the same row or column with the king.
Each player makes 2000 turns, if the white king wasn't checked by a black rook during those turns, black wins.
NN doesn't like losing, but thinks the task is too difficult for him, so he asks you to write a program that will always win playing for the white king. Note that Dasha can see your king and play depending on its position.
Input
In the beginning your program will receive 667 lines from input. Each line contains two integers x and y (1 β€ x, y β€ 999) β the piece's coordinates. The first line contains the coordinates of the king and the next 666 contain the coordinates of the rooks. The first coordinate denotes the number of the row where the piece is located, the second denotes the column. It is guaranteed that initially the king isn't in check and that all pieces occupy different squares.
Output
After getting king checked, you program should terminate immediately without printing anything extra.
Interaction
To make a move with the king, output two integers x and y (1 β€ x, y β€ 999) β the square to which the king would be moved. The king cannot move onto the square already occupied by a rook. It is guaranteed that the king would always have a valid move.
After each of your turns read the rook's turn in the following format: a single line containing three integers k, x and y (1 β€ k β€ 666, 1 β€ x_i, y_i β€ 999) β the number of the rook that would move and the square it would move to. It is guaranteed that the rook wouldn't move to a square already occupied by another chess piece, but it can move onto the square where it was before the turn so that its position wouldn't change. It is guaranteed that the move does not put your king into a check. If your king got in check, all three integers would be equal to -1 and in that case your program should terminate immediately.
After printing your turn do not forget to output end of line and flush the output. Otherwise you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
Answer "0 0 0" instead of a correct answer means that you made an invalid query. Exit immediately after receiving "0 0 0" and you will see Wrong answer verdict. Otherwise you can get an arbitrary verdict because your solution will continue to read from a closed stream.
Hacks are not allowed for this problem.
Example
Input
999 999
1 1
1 2
2 1
2 2
1 3
2 3
<...>
26 13
26 14
26 15
26 16
1 700 800
2 1 2
<...>
-1 -1 -1
Output
999 998
999 997
<...>
999 26
Note
The example is trimmed. The full initial positions of the rooks in the first test are available at <https://pastebin.com/qQCTXgKP>. It is not guaranteed that they will behave as in the example.
Submitted Solution:
```
from sys import stdout
moves = [(-1, -1), (1, -1), (-1, 1), (1, 1), (0, 1), (0, -1), (1, 0), (-1, 0)]
x, y = map(int, input().split())
rooks = [None] + [tuple(map(int, input().split())) for i in range(666)]
matrix = [[False] * 1000 for i in range(1000)]
for xx, yy in rooks[1:]:
matrix[xx][yy] = True
while (x, y) != (500, 500):
bestDis = 2000
for dx, dy in moves:
if 1 <= x + dx <= 999 and 1 <= y + dy <= 999 and not matrix[x+dx][y+dy]:
dis = max(abs(x + dx - 500), abs(y + dy - 500))
if dis < bestDis:
bestDis = dis
bestMove = dx, dy
x, y = x + bestMove[0], y + bestMove[1]
print(x, y)
stdout.flush()
idx, newx, newy = map(int, input().split())
if idx <= 0:
exit()
matrix[rooks[idx][0]][rooks[idx][1]] = False
rooks[idx] = newx, newy
matrix[newx][newy] = True
if sum(matrix[i][j] for i in range(1, 500) for j in range(1, 500)) <= 166:
dest = (1, 1)
elif sum(matrix[i][j] for i in range(501, 1000) for j in range(1, 500)) <= 166:
dest = (999, 1)
elif sum(matrix[i][j] for i in range(501, 1000) for j in range(501, 1000)) <= 166:
dest = (999, 999)
elif sum(matrix[i][j] for i in range(1, 500) for j in range(501, 1000)) <= 166:
dest = (1, 999)
else:
print('bad')
exit()
while (x, y) != dest:
bestDis = 2000
for dx, dy in moves:
if 1 <= x + dx <= 999 and 1 <= y + dy <= 999 and not matrix[x+dx][y+dy]:
dis = max(abs(x + dx - dest[0]), abs(y + dy - dest[1]))
if dis < bestDis:
bestDis = dis
bestMove = dx, dy
x, y = x + bestMove[0], y + bestMove[1]
print(x, y)
stdout.flush()
idx, newx, newy = map(int, input().split())
if idx <= 0:
exit()
matrix[rooks[idx][0]][rooks[idx][1]] = False
rooks[idx] = newx, newy
matrix[newx][newy] = True
``` | instruction | 0 | 72,533 | 15 | 145,066 |
No | output | 1 | 72,533 | 15 | 145,067 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive task.
Dasha and NN like playing chess. While playing a match they decided that normal chess isn't interesting enough for them, so they invented a game described below.
There are 666 black rooks and 1 white king on the chess board of size 999 Γ 999. The white king wins if he gets checked by rook, or, in other words, if he moves onto the square which shares either a row or column with a black rook.
The sides take turns, starting with white. NN plays as a white king and on each of his turns he moves a king to one of the squares that are adjacent to his current position either by side or diagonally, or, formally, if the king was on the square (x, y), it can move to the square (nx, ny) if and only max (|nx - x|, |ny - y|) = 1 , 1 β€ nx, ny β€ 999. NN is also forbidden from moving onto the squares occupied with black rooks, however, he can move onto the same row or column as a black rook.
Dasha, however, neglects playing by the chess rules, and instead of moving rooks normally she moves one of her rooks on any space devoid of other chess pieces. It is also possible that the rook would move onto the same square it was before and the position wouldn't change. However, she can't move the rook on the same row or column with the king.
Each player makes 2000 turns, if the white king wasn't checked by a black rook during those turns, black wins.
NN doesn't like losing, but thinks the task is too difficult for him, so he asks you to write a program that will always win playing for the white king. Note that Dasha can see your king and play depending on its position.
Input
In the beginning your program will receive 667 lines from input. Each line contains two integers x and y (1 β€ x, y β€ 999) β the piece's coordinates. The first line contains the coordinates of the king and the next 666 contain the coordinates of the rooks. The first coordinate denotes the number of the row where the piece is located, the second denotes the column. It is guaranteed that initially the king isn't in check and that all pieces occupy different squares.
Output
After getting king checked, you program should terminate immediately without printing anything extra.
Interaction
To make a move with the king, output two integers x and y (1 β€ x, y β€ 999) β the square to which the king would be moved. The king cannot move onto the square already occupied by a rook. It is guaranteed that the king would always have a valid move.
After each of your turns read the rook's turn in the following format: a single line containing three integers k, x and y (1 β€ k β€ 666, 1 β€ x_i, y_i β€ 999) β the number of the rook that would move and the square it would move to. It is guaranteed that the rook wouldn't move to a square already occupied by another chess piece, but it can move onto the square where it was before the turn so that its position wouldn't change. It is guaranteed that the move does not put your king into a check. If your king got in check, all three integers would be equal to -1 and in that case your program should terminate immediately.
After printing your turn do not forget to output end of line and flush the output. Otherwise you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
Answer "0 0 0" instead of a correct answer means that you made an invalid query. Exit immediately after receiving "0 0 0" and you will see Wrong answer verdict. Otherwise you can get an arbitrary verdict because your solution will continue to read from a closed stream.
Hacks are not allowed for this problem.
Example
Input
999 999
1 1
1 2
2 1
2 2
1 3
2 3
<...>
26 13
26 14
26 15
26 16
1 700 800
2 1 2
<...>
-1 -1 -1
Output
999 998
999 997
<...>
999 26
Note
The example is trimmed. The full initial positions of the rooks in the first test are available at <https://pastebin.com/qQCTXgKP>. It is not guaranteed that they will behave as in the example.
Submitted Solution:
```
from sys import stdout
coord = []#
xk, yk = map(int, input().split())
for t in range(666):
z = list(map(int, input().split()))
coord.append(z)
while True:
b1 = b2 = b3 = b4 = 0
for x, y in coord:
if x < xk and y > yk:
b1 += 1
elif x > xk and y > yk:
b2 += 1
elif x < xk and y < yk:
b3 += 1
elif x > xk and y < yk:
b4 += 1
q = max(2*b1 + b2 + b3, 2 * b2 + b1 + b4, 2 * b3 + b1 + b4, 2 * b4 + b2 + b3)
if (q == 2*b1 + b2 + b3) and [xk-1, yk+1] not in coord:
xk -= 1
yk += 1
elif (q == 2 * b2 + b1 + b4) and [xk+1, yk+1] not in coord:
xk += 1
yk += 1
elif (q == 2 * b3 + b1 + b4) and [xk-1, yk-1] not in coord:
xk -= 1
yk -= 1
elif (q == 2 * b4 + b2 + b3) and [xk+1, yk-1] not in coord:
xk += 1
yk -= 1
else:
ups = max(b1+b2, b2+b4, b3+b4, b1+b3)
if ups == b1+b2 and [xk, yk+1] not in coord:
yk += 1
elif ups == b2 + b4 and [xk+1, yk] not in coord:
xk += 1
elif ups == b3 + b4 and [xk, yk-1] not in coord:
yk -= 1
else:
xk -= 1
print(xk, yk)
stdout.flush()
k, x1, y1 = map(int, input().split())
if k == -1:
break
else:
coord[k-1] = [x1, y1]
``` | instruction | 0 | 72,534 | 15 | 145,068 |
No | output | 1 | 72,534 | 15 | 145,069 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an infinite checkered field. You should get from a square (x1; y1) to a square (x2; y2). Using the shortest path is not necessary. You can move on the field squares in four directions. That is, when you are positioned in any square, you can move to any other side-neighboring one.
A square (x; y) is considered bad, if at least one of the two conditions is fulfilled:
* |x + y| β‘ 0 (mod 2a),
* |x - y| β‘ 0 (mod 2b).
Your task is to find the minimum number of bad cells one will have to visit on the way from (x1; y1) to (x2; y2).
Input
The only line contains integers a, b, x1, y1, x2 and y2 β the parameters of the bad squares, the coordinates of the initial and the final squares correspondingly (2 β€ a, b β€ 109 and |x1|,|y1|,|x2|,|y2| β€ 109). It is guaranteed that the initial and the final square aren't bad.
Output
Print a single number β the minimum number of bad cells that one will have to visit in order to travel from square (x1; y1) to square (x2; y2).
Examples
Input
2 2 1 0 0 1
Output
1
Input
2 2 10 11 0 1
Output
5
Input
2 4 3 -1 3 7
Output
2
Note
In the third sample one of the possible paths in (3;-1)->(3;0)->(3;1)->(3;2)->(4;2)->(4;3)->(4;4)->(4;5)->(4;6)->(4;7)->(3;7). Squares (3;1) and (4;4) are bad. | instruction | 0 | 72,603 | 15 | 145,206 |
Tags: math
Correct Solution:
```
def f(a,b,x,y,z,w):
c=(x+y) // (2*a)
d=(z+w) // (2*a)
e=(x-y) // (2*b)
f=(z-w) // (2*b)
return max(abs(c-d),abs(e-f))
a,b,x,y,z,w=map(int,input().split())
print(f(a,b,x,y,z,w))
``` | output | 1 | 72,603 | 15 | 145,207 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an infinite checkered field. You should get from a square (x1; y1) to a square (x2; y2). Using the shortest path is not necessary. You can move on the field squares in four directions. That is, when you are positioned in any square, you can move to any other side-neighboring one.
A square (x; y) is considered bad, if at least one of the two conditions is fulfilled:
* |x + y| β‘ 0 (mod 2a),
* |x - y| β‘ 0 (mod 2b).
Your task is to find the minimum number of bad cells one will have to visit on the way from (x1; y1) to (x2; y2).
Input
The only line contains integers a, b, x1, y1, x2 and y2 β the parameters of the bad squares, the coordinates of the initial and the final squares correspondingly (2 β€ a, b β€ 109 and |x1|,|y1|,|x2|,|y2| β€ 109). It is guaranteed that the initial and the final square aren't bad.
Output
Print a single number β the minimum number of bad cells that one will have to visit in order to travel from square (x1; y1) to square (x2; y2).
Examples
Input
2 2 1 0 0 1
Output
1
Input
2 2 10 11 0 1
Output
5
Input
2 4 3 -1 3 7
Output
2
Note
In the third sample one of the possible paths in (3;-1)->(3;0)->(3;1)->(3;2)->(4;2)->(4;3)->(4;4)->(4;5)->(4;6)->(4;7)->(3;7). Squares (3;1) and (4;4) are bad. | instruction | 0 | 72,604 | 15 | 145,208 |
Tags: math
Correct Solution:
```
#!/usr/bin/python3
def cds(a, b, x, y):
return (x + y) // (2 * a), (x - y) // (2 * b)
def norm(x, y):
return max(x, y)
a, b, x1, y1, x2, y2 = map(int, input().split())
xp1, yp1 = cds(a, b, x1, y1)
xp2, yp2 = cds(a, b, x2, y2)
print(norm(abs(xp1 - xp2), abs(yp1 - yp2)))
``` | output | 1 | 72,604 | 15 | 145,209 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an infinite checkered field. You should get from a square (x1; y1) to a square (x2; y2). Using the shortest path is not necessary. You can move on the field squares in four directions. That is, when you are positioned in any square, you can move to any other side-neighboring one.
A square (x; y) is considered bad, if at least one of the two conditions is fulfilled:
* |x + y| β‘ 0 (mod 2a),
* |x - y| β‘ 0 (mod 2b).
Your task is to find the minimum number of bad cells one will have to visit on the way from (x1; y1) to (x2; y2).
Input
The only line contains integers a, b, x1, y1, x2 and y2 β the parameters of the bad squares, the coordinates of the initial and the final squares correspondingly (2 β€ a, b β€ 109 and |x1|,|y1|,|x2|,|y2| β€ 109). It is guaranteed that the initial and the final square aren't bad.
Output
Print a single number β the minimum number of bad cells that one will have to visit in order to travel from square (x1; y1) to square (x2; y2).
Examples
Input
2 2 1 0 0 1
Output
1
Input
2 2 10 11 0 1
Output
5
Input
2 4 3 -1 3 7
Output
2
Note
In the third sample one of the possible paths in (3;-1)->(3;0)->(3;1)->(3;2)->(4;2)->(4;3)->(4;4)->(4;5)->(4;6)->(4;7)->(3;7). Squares (3;1) and (4;4) are bad. | instruction | 0 | 72,605 | 15 | 145,210 |
Tags: math
Correct Solution:
```
a, b, x_1, y_1, x_2, y_2 = map(int, input().split())
a_b, a_e = (x_2 + y_2), (x_1 + y_1)
b_b, b_e = (x_2 - y_2), (x_1 - y_1)
if a_b > a_e:
a_b, a_e = a_e, a_b
if b_b > b_e:
b_b, b_e = b_e, b_b
if a_b % (2 * a) != 0:
a_b = (a_b // (2 * a) + 1) * (2 * a)
a_result, b_result = 0, 0
if a_b <= a_e:
a_result = (abs(a_e - a_b) + (2 * a - 1)) // (2 * a)
if b_b % (2 * b) != 0:
b_b = (b_b // (2 * b) + 1) * (2 * b)
if b_b <= b_e:
b_result = (abs(b_e - b_b) + (2 * b - 1)) // (2 * b)
print(max([a_result, b_result]))
``` | output | 1 | 72,605 | 15 | 145,211 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an infinite checkered field. You should get from a square (x1; y1) to a square (x2; y2). Using the shortest path is not necessary. You can move on the field squares in four directions. That is, when you are positioned in any square, you can move to any other side-neighboring one.
A square (x; y) is considered bad, if at least one of the two conditions is fulfilled:
* |x + y| β‘ 0 (mod 2a),
* |x - y| β‘ 0 (mod 2b).
Your task is to find the minimum number of bad cells one will have to visit on the way from (x1; y1) to (x2; y2).
Input
The only line contains integers a, b, x1, y1, x2 and y2 β the parameters of the bad squares, the coordinates of the initial and the final squares correspondingly (2 β€ a, b β€ 109 and |x1|,|y1|,|x2|,|y2| β€ 109). It is guaranteed that the initial and the final square aren't bad.
Output
Print a single number β the minimum number of bad cells that one will have to visit in order to travel from square (x1; y1) to square (x2; y2).
Examples
Input
2 2 1 0 0 1
Output
1
Input
2 2 10 11 0 1
Output
5
Input
2 4 3 -1 3 7
Output
2
Note
In the third sample one of the possible paths in (3;-1)->(3;0)->(3;1)->(3;2)->(4;2)->(4;3)->(4;4)->(4;5)->(4;6)->(4;7)->(3;7). Squares (3;1) and (4;4) are bad.
Submitted Solution:
```
a, b, x_1, y_1, x_2, y_2 = map(int, input().split())
print(max([abs((x_2 + y_2) - (x_1 + y_1)) // (2 * a),
abs((x_2 - y_2) - (x_1 - y_2)) // (2 * b)]))
``` | instruction | 0 | 72,606 | 15 | 145,212 |
No | output | 1 | 72,606 | 15 | 145,213 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an infinite checkered field. You should get from a square (x1; y1) to a square (x2; y2). Using the shortest path is not necessary. You can move on the field squares in four directions. That is, when you are positioned in any square, you can move to any other side-neighboring one.
A square (x; y) is considered bad, if at least one of the two conditions is fulfilled:
* |x + y| β‘ 0 (mod 2a),
* |x - y| β‘ 0 (mod 2b).
Your task is to find the minimum number of bad cells one will have to visit on the way from (x1; y1) to (x2; y2).
Input
The only line contains integers a, b, x1, y1, x2 and y2 β the parameters of the bad squares, the coordinates of the initial and the final squares correspondingly (2 β€ a, b β€ 109 and |x1|,|y1|,|x2|,|y2| β€ 109). It is guaranteed that the initial and the final square aren't bad.
Output
Print a single number β the minimum number of bad cells that one will have to visit in order to travel from square (x1; y1) to square (x2; y2).
Examples
Input
2 2 1 0 0 1
Output
1
Input
2 2 10 11 0 1
Output
5
Input
2 4 3 -1 3 7
Output
2
Note
In the third sample one of the possible paths in (3;-1)->(3;0)->(3;1)->(3;2)->(4;2)->(4;3)->(4;4)->(4;5)->(4;6)->(4;7)->(3;7). Squares (3;1) and (4;4) are bad.
Submitted Solution:
```
a, b, x_1, y_1, x_2, y_2 = map(int, input().split())
print(max([(abs((x_2 + y_2) - (x_1 + y_1)) + (2 * a - 1)) // (2 * a),
(abs((x_2 - y_2) - (x_1 - y_2)) + (2 * b - 1)) // (2 * b)]))
``` | instruction | 0 | 72,607 | 15 | 145,214 |
No | output | 1 | 72,607 | 15 | 145,215 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Pavel loves grid mazes. A grid maze is an n Γ m rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side.
Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any other one. Pavel doesn't like it when his maze has too little walls. He wants to turn exactly k empty cells into walls so that all the remaining cells still formed a connected area. Help him.
Input
The first line contains three integers n, m, k (1 β€ n, m β€ 500, 0 β€ k < s), where n and m are the maze's height and width, correspondingly, k is the number of walls Pavel wants to add and letter s represents the number of empty cells in the original maze.
Each of the next n lines contains m characters. They describe the original maze. If a character on a line equals ".", then the corresponding cell is empty and if the character equals "#", then the cell is a wall.
Output
Print n lines containing m characters each: the new maze that fits Pavel's requirements. Mark the empty cells that you transformed into walls as "X", the other cells must be left without changes (that is, "." and "#").
It is guaranteed that a solution exists. If there are multiple solutions you can output any of them.
Examples
Input
3 4 2
#..#
..#.
#...
Output
#.X#
X.#.
#...
Input
5 4 5
#...
#.#.
.#..
...#
.#.#
Output
#XXX
#X#.
X#..
...#
.#.# | instruction | 0 | 72,831 | 15 | 145,662 |
Tags: dfs and similar
Correct Solution:
```
import sys
import math
sys.setrecursionlimit(300000)
MAXNUM = math.inf
MINNUM = -1 * math.inf
def getInt():
return int(sys.stdin.readline().rstrip())
def getInts():
return map(int, sys.stdin.readline().rstrip().split(" "))
def getString():
return sys.stdin.readline().rstrip()
def printOutput(ans):
for line in ans:
for ele in line:
sys.stdout.write(ele)
sys.stdout.write("\n")
def emptySquares(g):
total = 0
firstEmpty = None
for i in range(len(g)):
for j in range(len(g[0])):
if g[i][j] != "#":
total += 1
firstEmpty = (i, j)
return total, firstEmpty
toDelete = []
def dfs(grid, visited, toSave, x, y):
if (x, y) not in visited:
visited[(x, y)] = True
if toSave:
toSave -= 1
else:
toDelete.append((x, y))
for i, j in zip((-1, 1, 0, 0), (0, 0, 1, -1)):
if (
-1 < x + i < len(grid)
and -1 < y + j < len(grid[0])
and (x + i, y + j) not in visited
and grid[x + i][y + j] != "#"
):
toSave = dfs(grid, visited, toSave, x + i, y + j)
return toSave
def iterativedfs(grid, toSave, x, y):
stack = [(x, y)]
visited = {}
visited[(x,y)] = True
toDelete = []
while stack:
x, y = stack.pop()
if toSave != 0:
toSave -= 1
else:
toDelete.append((x, y))
for i, j in zip((-1, 1, 0, 0), (0, 0, 1, -1)):
if (
-1 < x + i < len(grid)
and -1 < y + j < len(grid[0])
and (x + i, y + j) not in visited
and grid[x + i][y + j] != "#"
):
stack.append((x + i, y + j))
visited[(x+i, y+j)] = True
return toDelete
def solve(n, m, k, grid):
if k == 0:
return grid
empty, firstEmpty = emptySquares(grid)
x, y = firstEmpty
toDelete = iterativedfs(grid, empty - k, x, y)
for a, b in toDelete:
grid[a][b] = "X"
return grid
def readinput():
n, m, k = getInts()
grid = []
for _ in range(n):
grid.append([i for i in getString()])
printOutput(solve(n, m, k, grid))
readinput()
``` | output | 1 | 72,831 | 15 | 145,663 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Pavel loves grid mazes. A grid maze is an n Γ m rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side.
Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any other one. Pavel doesn't like it when his maze has too little walls. He wants to turn exactly k empty cells into walls so that all the remaining cells still formed a connected area. Help him.
Input
The first line contains three integers n, m, k (1 β€ n, m β€ 500, 0 β€ k < s), where n and m are the maze's height and width, correspondingly, k is the number of walls Pavel wants to add and letter s represents the number of empty cells in the original maze.
Each of the next n lines contains m characters. They describe the original maze. If a character on a line equals ".", then the corresponding cell is empty and if the character equals "#", then the cell is a wall.
Output
Print n lines containing m characters each: the new maze that fits Pavel's requirements. Mark the empty cells that you transformed into walls as "X", the other cells must be left without changes (that is, "." and "#").
It is guaranteed that a solution exists. If there are multiple solutions you can output any of them.
Examples
Input
3 4 2
#..#
..#.
#...
Output
#.X#
X.#.
#...
Input
5 4 5
#...
#.#.
.#..
...#
.#.#
Output
#XXX
#X#.
X#..
...#
.#.# | instruction | 0 | 72,832 | 15 | 145,664 |
Tags: dfs and similar
Correct Solution:
```
n, m, k = map(int, input().split())
maze = [["#"]*(m+2)]+[list("#"+input()+"#") for i in range(n)]+[["#"]*(m+2)]
steps = [[0,1],[0,-1],[1,0],[-1,0]]
empty = -k
x, y = None, None
for i in range(n+2):
empty += maze[i].count(".")
for j in range(m+2):
if maze[i][j] == ".":
x, y = i, j
break
stack = [(x,y)]
while empty:
(x, y) = stack.pop()
if maze[x][y] == "v":
continue
for dx, dy in steps:
if maze[x+dx][y+dy] == ".":
stack.append((x+dx, y+dy))
maze[x][y] = "v"
empty -= 1
for row in maze[1:-1]:
print("".join(row[1:-1]).replace(".","X").replace("v","."))
# Made By Mostafa_Khaled
``` | output | 1 | 72,832 | 15 | 145,665 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Pavel loves grid mazes. A grid maze is an n Γ m rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side.
Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any other one. Pavel doesn't like it when his maze has too little walls. He wants to turn exactly k empty cells into walls so that all the remaining cells still formed a connected area. Help him.
Input
The first line contains three integers n, m, k (1 β€ n, m β€ 500, 0 β€ k < s), where n and m are the maze's height and width, correspondingly, k is the number of walls Pavel wants to add and letter s represents the number of empty cells in the original maze.
Each of the next n lines contains m characters. They describe the original maze. If a character on a line equals ".", then the corresponding cell is empty and if the character equals "#", then the cell is a wall.
Output
Print n lines containing m characters each: the new maze that fits Pavel's requirements. Mark the empty cells that you transformed into walls as "X", the other cells must be left without changes (that is, "." and "#").
It is guaranteed that a solution exists. If there are multiple solutions you can output any of them.
Examples
Input
3 4 2
#..#
..#.
#...
Output
#.X#
X.#.
#...
Input
5 4 5
#...
#.#.
.#..
...#
.#.#
Output
#XXX
#X#.
X#..
...#
.#.# | instruction | 0 | 72,833 | 15 | 145,666 |
Tags: dfs and similar
Correct Solution:
```
import sys
import threading
n,m,k = map(int,input().split())
matrix = []
for i in range(n):
row = input()
r=[]
for j in range(len(row)):
r.append(row[j])
matrix.append(r)
number_of_empty_cell = 0
global count
count = 0
for i in range(n):
for j in range(m):
if matrix[i][j]==".":
number_of_empty_cell+=1
def isSafe(i,j):
return True if 0<= i < n and 0<= j < m else False
def boarder_check(i,j):
return True if i==0 or j==0 or i==n-1 or j==m-1 else False
def dfs(i,j):
global count
if count < number_of_empty_cell-k:
matrix[i][j]="$"
count+=1
if isSafe(i,j+1) and matrix[i][j+1]==".":
dfs(i,j+1)
if isSafe(i+1,j) and matrix[i+1][j]==".":
dfs(i+1,j)
if isSafe(i,j-1) and matrix[i][j-1]==".":
dfs(i,j-1)
if isSafe(i-1,j) and matrix[i-1][j]==".":
dfs(i-1,j)
def main():
for i in range(n):
for j in range(m):
if matrix[i][j]==".":
dfs(i,j)
for i in range(n):
for j in range(m):
if matrix[i][j]=="$":
matrix[i][j]="."
elif matrix[i][j]==".":
matrix[i][j] = "X"
for i in range(n):
s = "".join(matrix[i])
print(s,end="\n")
if __name__ == "__main__":
sys.setrecursionlimit(10**6)
threading.stack_size(10**8)
t = threading.Thread(target=main)
t.start()
t.join()
``` | output | 1 | 72,833 | 15 | 145,667 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Pavel loves grid mazes. A grid maze is an n Γ m rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side.
Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any other one. Pavel doesn't like it when his maze has too little walls. He wants to turn exactly k empty cells into walls so that all the remaining cells still formed a connected area. Help him.
Input
The first line contains three integers n, m, k (1 β€ n, m β€ 500, 0 β€ k < s), where n and m are the maze's height and width, correspondingly, k is the number of walls Pavel wants to add and letter s represents the number of empty cells in the original maze.
Each of the next n lines contains m characters. They describe the original maze. If a character on a line equals ".", then the corresponding cell is empty and if the character equals "#", then the cell is a wall.
Output
Print n lines containing m characters each: the new maze that fits Pavel's requirements. Mark the empty cells that you transformed into walls as "X", the other cells must be left without changes (that is, "." and "#").
It is guaranteed that a solution exists. If there are multiple solutions you can output any of them.
Examples
Input
3 4 2
#..#
..#.
#...
Output
#.X#
X.#.
#...
Input
5 4 5
#...
#.#.
.#..
...#
.#.#
Output
#XXX
#X#.
X#..
...#
.#.# | instruction | 0 | 72,834 | 15 | 145,668 |
Tags: dfs and similar
Correct Solution:
```
from collections import deque
def neighbours(v):
out = set()
x, y = v
if 0 <= x + 1 < m and 0 <= y < n:
out.add((x + 1, y))
if 0 <= x - 1 < m and 0 <= y < n:
out.add((x - 1, y))
if 0 <= x < m and 0 <= y + 1 < n:
out.add((x, y + 1))
if 0 <= x < m and 0 <= y - 1 < n:
out.add((x, y - 1))
return out
def bfs(v):
queue = deque([v])
visited_dots = 0
while queue:
vx, vy = queue.popleft()
if g[vy][vx] == 2:
continue
g[vy][vx] = 2
visited_dots += 1
if visited_dots == dots - k:
return
for ux, uy in neighbours((vx, vy)):
if g[uy][ux] == 0:
queue.append((ux, uy))
n, m, k = map(int, input().split())
g = []
visited = set()
dots = 0
v = None
for j in range(n):
s = list(map(lambda x: 0 if x == '.' else 1, input()))
if not v and 0 in s:
v = (s.index(0), j)
dots += m - sum(s)
g.append(s)
bfs(v)
for j in range(n):
for i in range(m):
if g[j][i] == 0:
print('X', end='')
elif g[j][i] == 1:
print('#', end='')
else:
print('.', end='')
print()
``` | output | 1 | 72,834 | 15 | 145,669 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Pavel loves grid mazes. A grid maze is an n Γ m rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side.
Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any other one. Pavel doesn't like it when his maze has too little walls. He wants to turn exactly k empty cells into walls so that all the remaining cells still formed a connected area. Help him.
Input
The first line contains three integers n, m, k (1 β€ n, m β€ 500, 0 β€ k < s), where n and m are the maze's height and width, correspondingly, k is the number of walls Pavel wants to add and letter s represents the number of empty cells in the original maze.
Each of the next n lines contains m characters. They describe the original maze. If a character on a line equals ".", then the corresponding cell is empty and if the character equals "#", then the cell is a wall.
Output
Print n lines containing m characters each: the new maze that fits Pavel's requirements. Mark the empty cells that you transformed into walls as "X", the other cells must be left without changes (that is, "." and "#").
It is guaranteed that a solution exists. If there are multiple solutions you can output any of them.
Examples
Input
3 4 2
#..#
..#.
#...
Output
#.X#
X.#.
#...
Input
5 4 5
#...
#.#.
.#..
...#
.#.#
Output
#XXX
#X#.
X#..
...#
.#.# | instruction | 0 | 72,835 | 15 | 145,670 |
Tags: dfs and similar
Correct Solution:
```
## necessary imports
import sys
input = sys.stdin.readline
from math import log2, log, ceil
# swap_array function
def swaparr(arr, a,b):
temp = arr[a];
arr[a] = arr[b];
arr[b] = temp
## gcd function
def gcd(a,b):
if a == 0:
return b
return gcd(b%a, a)
## nCr function efficient using Binomial Cofficient
def nCr(n, k):
if(k > n - k):
k = n - k
res = 1
for i in range(k):
res = res * (n - i)
res = res / (i + 1)
return res
## upper bound function code -- such that e in a[:i] e < x;
def upper_bound(a, x, lo=0):
hi = len(a)
while lo < hi:
mid = (lo+hi)//2
if a[mid] < x:
lo = mid+1
else:
hi = mid
return lo
## prime factorization
def primefs(n):
## if n == 1 ## calculating primes
primes = {}
while(n%2 == 0):
primes[2] = primes.get(2, 0) + 1
n = n//2
for i in range(3, int(n**0.5)+2, 2):
while(n%i == 0):
primes[i] = primes.get(i, 0) + 1
n = n//i
if n > 2:
primes[n] = primes.get(n, 0) + 1
## prime factoriazation of n is stored in dictionary
## primes and can be accesed. O(sqrt n)
return primes
## MODULAR EXPONENTIATION FUNCTION
def power(x, y, p):
res = 1
x = x % p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) :
res = (res * x) % p
y = y >> 1
x = (x * x) % p
return res
## DISJOINT SET UNINON FUNCTIONS
def swap(a,b):
temp = a
a = b
b = temp
return a,b
# find function
def find(x, link):
while(x != link[x]):
x = link[x]
return x
# the union function which makes union(x,y)
# of two nodes x and y
def union(x, y, link, size):
x = find(x, link)
y = find(y, link)
if size[x] < size[y]:
x,y = swap(x,y)
if x != y:
size[x] += size[y]
link[y] = x
## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES
def sieve(n):
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
return prime
#### PRIME FACTORIZATION IN O(log n) using Sieve ####
MAXN = int(1e6 + 5)
def spf_sieve():
spf[1] = 1;
for i in range(2, MAXN):
spf[i] = i;
for i in range(4, MAXN, 2):
spf[i] = 2;
for i in range(3, ceil(MAXN ** 0.5), 2):
if spf[i] == i:
for j in range(i*i, MAXN, i):
if spf[j] == j:
spf[j] = i;
## function for storing smallest prime factors (spf) in the array
################## un-comment below 2 lines when using factorization #################
# spf = [0 for i in range(MAXN)]
# spf_sieve()
def factoriazation(x):
ret = {};
while x != 1:
ret[spf[x]] = ret.get(spf[x], 0) + 1;
x = x//spf[x]
return ret
## this function is useful for multiple queries only, o/w use
## primefs function above. complexity O(log n)
## taking integer array input
def int_array():
return list(map(int, input().strip().split()))
## taking string array input
def str_array():
return input().strip().split();
#defining a couple constants
MOD = int(1e9)+7;
CMOD = 998244353;
INF = float('inf'); NINF = -float('inf');
################### ---------------- TEMPLATE ENDS HERE ---------------- ###################
n, m, k = int_array();
maze = [list(input().strip()) for _ in range(n)];
dick = {}; count = 0;
revs_dick = {};
safe = 0;
for i in range(n):
for j in range(m):
if maze[i][j] == '.':
safe += 1;
dick[(i,j)] = count;
revs_dick[count] = (i,j);
count += 1;
# def dfs(x):
# global total_nodes
# if visited[x] or total_nodes == (safe-k):
# return
# visited[x] = True;
# total_nodes += 1;
# if total_nodes == (safe-k):
# return
# for i in graph[x]:
# dfs(i);
## dfs using stack (iterative);
def dfs():
global total_nodes
while stack:
x = stack.pop();
if visited[x] or total_nodes == (safe - k):
continue
visited[x] = True
total_nodes += 1;
if total_nodes == (safe-k):
continue;
for i in graph[x]:
stack.append(i);
graph = [[] for _ in range(count+1)];
for i in range(n):
for j in range(m):
ours = (i, j);
if ours in dick:
up = (i-1, j)
if up in dick:
graph[dick[ours]].append(dick[up]);
down = (i+1, j)
if down in dick:
graph[dick[ours]].append(dick[down]);
left = (i, j-1);
if left in dick:
graph[dick[ours]].append(dick[left]);
right = (i, j+1);
if right in dick:
graph[dick[ours]].append(dick[right]);
visited = [False]*(count); stack = [0];
total_nodes = 0;
dfs();
for i in range(count):
if not visited[i]:
x,y = revs_dick[i];
maze[x][y] = 'X';
for i in maze:
print(''.join(i));
``` | output | 1 | 72,835 | 15 | 145,671 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Pavel loves grid mazes. A grid maze is an n Γ m rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side.
Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any other one. Pavel doesn't like it when his maze has too little walls. He wants to turn exactly k empty cells into walls so that all the remaining cells still formed a connected area. Help him.
Input
The first line contains three integers n, m, k (1 β€ n, m β€ 500, 0 β€ k < s), where n and m are the maze's height and width, correspondingly, k is the number of walls Pavel wants to add and letter s represents the number of empty cells in the original maze.
Each of the next n lines contains m characters. They describe the original maze. If a character on a line equals ".", then the corresponding cell is empty and if the character equals "#", then the cell is a wall.
Output
Print n lines containing m characters each: the new maze that fits Pavel's requirements. Mark the empty cells that you transformed into walls as "X", the other cells must be left without changes (that is, "." and "#").
It is guaranteed that a solution exists. If there are multiple solutions you can output any of them.
Examples
Input
3 4 2
#..#
..#.
#...
Output
#.X#
X.#.
#...
Input
5 4 5
#...
#.#.
.#..
...#
.#.#
Output
#XXX
#X#.
X#..
...#
.#.# | instruction | 0 | 72,836 | 15 | 145,672 |
Tags: dfs and similar
Correct Solution:
```
from collections import*
n, m, k = map(int, input(). split())
b = [input() for _ in range(n)]
c = [[[] for z in range(m)] for _ in range(n)]
ans = 0
r = [[0] * m for i in range(n)]
s = 0
q, w = -1, -1
def f(i, y):
an = []
if i > 0:
an.append([i - 1, y])
if y > 0:
an.append([i, y - 1])
if i < n - 1:
an.append([i + 1, y])
if y < m - 1:
an.append([i, y + 1])
return an
for i in range(n):
for y in range(m):
if b[i][y] == '.':
s += 1
q = i
w = y
for j in f(i, y):
if b[j[0]][j[1]] == '.':
c[i][y].append(j)
def dfs(i, y):
global ans
d = deque()
d.append([i, y])
ans = 1
r[i][y] = 1
while ans != s - k:
z = d.pop()
i, y = z[0], z[1]
r[i][y] = 1
for x in range(len(c[i][y])):
if r[c[i][y][x][0]][c[i][y][x][1]] == 0:
d.append([c[i][y][x][0], c[i][y][x][1]])
r[c[i][y][x][0]][c[i][y][x][1]] = 1
ans += 1
if ans == s - k:
break
if not (q == w == -1):
dfs(q, w)
for i in range(n):
for y in range(m):
if b[i][y] == '.' and r[i][y] == 0:
r[i][y] = 'X'
else:
r[i][y] = b[i][y]
for i in range(n):
print(''.join(r[i]))
``` | output | 1 | 72,836 | 15 | 145,673 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Pavel loves grid mazes. A grid maze is an n Γ m rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side.
Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any other one. Pavel doesn't like it when his maze has too little walls. He wants to turn exactly k empty cells into walls so that all the remaining cells still formed a connected area. Help him.
Input
The first line contains three integers n, m, k (1 β€ n, m β€ 500, 0 β€ k < s), where n and m are the maze's height and width, correspondingly, k is the number of walls Pavel wants to add and letter s represents the number of empty cells in the original maze.
Each of the next n lines contains m characters. They describe the original maze. If a character on a line equals ".", then the corresponding cell is empty and if the character equals "#", then the cell is a wall.
Output
Print n lines containing m characters each: the new maze that fits Pavel's requirements. Mark the empty cells that you transformed into walls as "X", the other cells must be left without changes (that is, "." and "#").
It is guaranteed that a solution exists. If there are multiple solutions you can output any of them.
Examples
Input
3 4 2
#..#
..#.
#...
Output
#.X#
X.#.
#...
Input
5 4 5
#...
#.#.
.#..
...#
.#.#
Output
#XXX
#X#.
X#..
...#
.#.# | instruction | 0 | 72,837 | 15 | 145,674 |
Tags: dfs and similar
Correct Solution:
```
import sys
import math
import collections
import heapq
import decimal
n,m,k=(int(i) for i in input().split())
l=[]
for i in range(n):
l.append(list(input()))
def neighbours(x,y):
global n
global m
global l
l1=[]
if(x-1>=0 and l[x-1][y]=='.'):
l1.append((x-1,y))
if(x+1<=n-1 and l[x+1][y]=='.'):
l1.append((x+1,y))
if(y-1>=0 and l[x][y-1]=='.'):
l1.append((x,y-1))
if(y+1<=m-1 and l[x][y+1]=='.'):
l1.append((x,y+1))
return l1
d={}
c1=0
for i in range(n):
for j in range(m):
d[(i,j)]=[]
for i in range(n):
for j in range(m):
if(l[i][j]=='.'):
c1+=1
nbd=neighbours(i,j)
for x in nbd:
d[(i,j)].append(x)
c=0
v=[[0 for i in range(m)] for j in range(n)]
if(c1==0):
for i in range(n):
print(''.join(l[i]))
else:
queue=[]
for i in range(n):
if(c==1):
break
for j in range(m):
if(l[i][j]=='.'):
queue.append((i,j))
l[i][j]='X'
v[i][j]=1
c+=1
break
while(queue!=[]):
if(c==c1-k):
break
s=queue.pop(0)
for j in d[s]:
if(c==c1-k):
break
if(v[j[0]][j[1]]==0):
v[j[0]][j[1]]=1
l[j[0]][j[1]]='X'
c+=1
queue.append(j)
for i in range(n):
for j in range(m):
if(l[i][j]=='X'):
l[i][j]='.'
elif(l[i][j]=='.'):
l[i][j]='X'
for i in range(n):
print(''.join(l[i]))
``` | output | 1 | 72,837 | 15 | 145,675 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Pavel loves grid mazes. A grid maze is an n Γ m rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side.
Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any other one. Pavel doesn't like it when his maze has too little walls. He wants to turn exactly k empty cells into walls so that all the remaining cells still formed a connected area. Help him.
Input
The first line contains three integers n, m, k (1 β€ n, m β€ 500, 0 β€ k < s), where n and m are the maze's height and width, correspondingly, k is the number of walls Pavel wants to add and letter s represents the number of empty cells in the original maze.
Each of the next n lines contains m characters. They describe the original maze. If a character on a line equals ".", then the corresponding cell is empty and if the character equals "#", then the cell is a wall.
Output
Print n lines containing m characters each: the new maze that fits Pavel's requirements. Mark the empty cells that you transformed into walls as "X", the other cells must be left without changes (that is, "." and "#").
It is guaranteed that a solution exists. If there are multiple solutions you can output any of them.
Examples
Input
3 4 2
#..#
..#.
#...
Output
#.X#
X.#.
#...
Input
5 4 5
#...
#.#.
.#..
...#
.#.#
Output
#XXX
#X#.
X#..
...#
.#.# | instruction | 0 | 72,838 | 15 | 145,676 |
Tags: dfs and similar
Correct Solution:
```
def dfs(mat, r, c, visited, limit):
dfsStack = [(r,c)]
while dfsStack and limit > 0:
i, j = dfsStack.pop()
if 0 <= i < len(mat) and 0 <= j < len(mat[i]) and mat[i][j] == "." and not visited[i][j]:
mat[i][j] = "C"
visited[i][j] = True
limit -= 1
dfsStack.append((i + 1, j))
dfsStack.append((i - 1, j))
dfsStack.append((i, j - 1))
dfsStack.append((i, j + 1))
# main method
height, width, walls = map(int, input().split())
empty = 0
mat = []
visited = []
i = -1
j = -1
for r in range(height):
line = input()
if i == j == -1 and line.find(".") > -1:
i = r
j = line.index(".")
mat.append(list(line))
visited.append([False] * len(line))
empty += line.count(".")
emptyLeft = empty - walls
# we want to get an {emptyLeft} size connected component
# then mark all the other empty cells as walls
dfs(mat, i, j, visited, emptyLeft)
# mark connected component as empty first
# other empty cells changed to walls
# print mat
for i in range(height):
line = "".join(mat[i])
print(line.replace(".", "X").replace("C", "."))
``` | output | 1 | 72,838 | 15 | 145,677 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Pavel loves grid mazes. A grid maze is an n Γ m rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side.
Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any other one. Pavel doesn't like it when his maze has too little walls. He wants to turn exactly k empty cells into walls so that all the remaining cells still formed a connected area. Help him.
Input
The first line contains three integers n, m, k (1 β€ n, m β€ 500, 0 β€ k < s), where n and m are the maze's height and width, correspondingly, k is the number of walls Pavel wants to add and letter s represents the number of empty cells in the original maze.
Each of the next n lines contains m characters. They describe the original maze. If a character on a line equals ".", then the corresponding cell is empty and if the character equals "#", then the cell is a wall.
Output
Print n lines containing m characters each: the new maze that fits Pavel's requirements. Mark the empty cells that you transformed into walls as "X", the other cells must be left without changes (that is, "." and "#").
It is guaranteed that a solution exists. If there are multiple solutions you can output any of them.
Examples
Input
3 4 2
#..#
..#.
#...
Output
#.X#
X.#.
#...
Input
5 4 5
#...
#.#.
.#..
...#
.#.#
Output
#XXX
#X#.
X#..
...#
.#.#
Submitted Solution:
```
# ------------------------------------------------------
def printTheLab():
global n
global m
global lab
for i in range(n):
s = ''
for j in range(m):
if (lab[i][j] == 0) or (lab[i][j] == -1):
s += '.'
elif lab[i][j] == 1:
s += '#'
elif lab[i][j] == 2:
s += 'X'
else:
s += '?'
print(s)
# -------- main program --------------------------------
n, m, k = map(int, input().split())
lab = []
lab_path = [] # Π² ΠΊΠ°ΠΆΠ΄ΡΠΉ ΡΠ»Π΅ΠΌΠ΅Π½Ρ Π΄ΠΎΠ±Π°Π²Π»ΡΠ΅ΠΌ
for i in range(n):
s = input()
s1 = s.replace('#', '1 ')
s2 = s1.replace('.', '0 ')
stroka_lab = list(map(int, s2.split()))
lab.append(stroka_lab)
stroka_lab_path = [[-1, -1] for j in range(m)]
lab_path.append(stroka_lab_path)
# print(lab)
# print(lab_path)
# Π² lab_path Π² ΠΊΠ°ΠΆΠ΄ΠΎΠΉ ΠΊΠ»Π΅ΡΠΊΠ΅ Ρ
ΡΠ°Π½ΡΡΡΡ Π΄Π²Π΅ ΠΊΠΎΠΎΡΠ΄ΠΈΠ½Π°ΡΡ - ΠΠ’ΠΠ£ΠΠ Π² ΡΡΡ ΠΊΠ»Π΅ΡΠΊΡ ΠΏΡΠΈΡΠ»ΠΈ
# Π½Π°ΠΉΡΠΈ ΠΏΠ΅ΡΠ²ΡΡ ΠΏΡΡΡΡΡ ΠΊΠ»Π΅ΡΠΊΡ
emptyFound = False
i = 0
while not emptyFound:
row1 = i//m
col1 = i%m
if lab[row1][col1] == 0:
emptyFound = True
i += 1
# row1, col1 - ΡΡΡΠΎΠΊΠ° ΠΈ ΡΡΠΎΠ»Π±Π΅Ρ ΠΏΠ΅ΡΠ²ΠΎΠΉ ΠΏΡΡΡΠΎΠΉ ΠΊΠ»Π΅ΡΠΊΠΈ
i = row1
j = col1
while k > 0:
lab[i][j] = -1 # ΠΌΠΈΠ½ΡΡ ΠΎΠ΄ΠΈΠ½ - Π½Π°Ρ ΠΏΡΡΡ
if (j > 0) and (lab[i][j - 1] == 0): # ΠΌΠΎΠΆΠ½ΠΎ ΠΏΡΠΎΠ±ΠΎΠ²Π°ΡΡ Π²Π»Π΅Π²ΠΎ
lab_path[i][j-1][0] = i
lab_path[i][j-1][1] = j
# ΠΏΠ΅ΡΠ΅Ρ
ΠΎΠ΄ Π²Π»Π΅Π²ΠΎ
i = i
j -= 1
elif (i<n-1) and (lab[i+1][j]==0): # ΠΌΠΎΠΆΠ½ΠΎ ΠΏΡΠΎΠ±ΠΎΠ²Π°ΡΡ Π²Π½ΠΈΠ·
lab_path[i+1][j][0] = i
lab_path[i+1][j][1] = j
# ΠΏΠ΅ΡΠ΅Ρ
ΠΎΠ΄ Π²Π½ΠΈΠ·
i += 1
j = j
elif (j<m-1) and (lab[i][j+1]==0): # ΠΌΠΎΠΆΠ½ΠΎ ΠΏΡΠΎΠ±ΠΎΠ²Π°ΡΡ Π²ΠΏΡΠ°Π²ΠΎ
lab_path[i][j+1][0] = i
lab_path[i][j+1][1] = j
# ΠΏΠ΅ΡΠ΅Ρ
ΠΎΠ΄ Π²ΠΏΡΠ°Π²ΠΎ
i = i
j += 1
elif (i>0) and (lab[i-1][j]==0): # ΠΌΠΎΠΆΠ½ΠΎ ΠΏΡΠΎΠ±ΠΎΠ²Π°ΡΡ Π²Π²Π΅ΡΡ
lab_path[i-1][j][0] = i
lab_path[i-1][j][1] = j
# ΠΏΠ΅ΡΠ΅Ρ
ΠΎΠ΄ Π²Π²Π΅ΡΡ
i -= 1
j = j
else:
# ΠΈΠ· ΡΡΠΎΠΉ ΠΊΠ»Π΅ΡΠΊΠΈ ΠΈΠ΄ΡΠΈ ΡΠΆΠ΅ Π½Π΅ΠΊΡΠ΄Π°
# Π·Π΄Π΅ΡΡ ΠΈ ΡΡΠ°Π²ΠΈΠΌ ΡΡΠ΅Π½Ρ
lab[i][j] = 2 # Π΄Π²ΠΎΠΉΠΊΠ° - ΡΡΠ΅Π½Π°
k -= 1
# ΠΈ ΠΏΠ΅ΡΠ΅Ρ
ΠΎΠ΄ΠΈΠΌ ΠΎΠ±ΡΠ°ΡΠ½ΠΎ
i1 = lab_path[i][j][0]
j1 = lab_path[i][j][1]
if (i1==-1) and (j1==-1):
# ΠΊΡΠ΄Π° ΠΈΠ΄ΡΠΈ ΠΈΠ· ΠΏΠ΅ΡΠ²ΠΎΠΉ ΠΊΠ»Π΅ΡΠΊΠΈ?
# Π½Π°ΠΉΡΠΈ ΡΠ²ΠΎΠ±ΠΎΠ΄Π½ΡΡ
if (j1 > 0) and (lab[i1][j1 - 1] == 0): # ΠΌΠΎΠΆΠ½ΠΎ ΠΏΡΠΎΠ±ΠΎΠ²Π°ΡΡ Π²Π»Π΅Π²ΠΎ
i1 = i1
j1 -= 1
elif (i1 < n - 1) and (lab[i1 + 1][j1] == 0): # ΠΌΠΎΠΆΠ½ΠΎ ΠΏΡΠΎΠ±ΠΎΠ²Π°ΡΡ Π²Π½ΠΈΠ·
i1 += 1
j1 = j1
elif (j1 < m - 1) and (lab[i1][j1 + 1] == 0): # ΠΌΠΎΠΆΠ½ΠΎ ΠΏΡΠΎΠ±ΠΎΠ²Π°ΡΡ Π²ΠΏΡΠ°Π²ΠΎ
i1 = i1
j1 += 1
else: # Π’Π£Π’ Π£Π Π’ΠΠ§ΠΠ (i1 > 0) and (lab[i1 - 1][j1] == 0): # ΠΌΠΎΠΆΠ½ΠΎ ΠΏΡΠΎΠ±ΠΎΠ²Π°ΡΡ Π²Π²Π΅ΡΡ
i1 -= 1
j1 = j1
else:
i = i1
j = j1
printTheLab()
``` | instruction | 0 | 72,839 | 15 | 145,678 |
Yes | output | 1 | 72,839 | 15 | 145,679 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Pavel loves grid mazes. A grid maze is an n Γ m rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side.
Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any other one. Pavel doesn't like it when his maze has too little walls. He wants to turn exactly k empty cells into walls so that all the remaining cells still formed a connected area. Help him.
Input
The first line contains three integers n, m, k (1 β€ n, m β€ 500, 0 β€ k < s), where n and m are the maze's height and width, correspondingly, k is the number of walls Pavel wants to add and letter s represents the number of empty cells in the original maze.
Each of the next n lines contains m characters. They describe the original maze. If a character on a line equals ".", then the corresponding cell is empty and if the character equals "#", then the cell is a wall.
Output
Print n lines containing m characters each: the new maze that fits Pavel's requirements. Mark the empty cells that you transformed into walls as "X", the other cells must be left without changes (that is, "." and "#").
It is guaranteed that a solution exists. If there are multiple solutions you can output any of them.
Examples
Input
3 4 2
#..#
..#.
#...
Output
#.X#
X.#.
#...
Input
5 4 5
#...
#.#.
.#..
...#
.#.#
Output
#XXX
#X#.
X#..
...#
.#.#
Submitted Solution:
```
import random, math, sys
from copy import deepcopy as dc
from bisect import bisect_left, bisect_right
from collections import Counter
input = sys.stdin.readline
# Function to take input
def input_test():
n, m, k = map(int, input().strip().split(" "))
grid = []
for i in range(n):
grid.append(list(input().strip()))
def dfsUtil(i, j):
nonlocal n, m, k, grid
adj = [
[0, 1], [0, -1], [1, 0], [-1, 0]
]
stack = [[i, j]]
while stack:
if k <= 0:
return
i, j = stack[-1][0], stack[-1][1]
stack.pop()
for kj in adj:
ni, nj = i + kj[0], j+ kj[1]
if 0 <= ni < n and 0 <= nj < m and grid[ni][nj] == ".":
if k <= 0:
return
grid[ni][nj] = "Y"
k -= 1
# print(i, j, "=>", ni, nj, "K = ", k)
stack.append([ni, nj])
li, lj = 0, 0
s = 0
for i in range(n):
for j in range(m):
if grid[i][j] == ".":
s += 1
li, lj = i+1-1, j+1-1
k = s - k - 1
grid[li][lj] = "Y"
dfsUtil(li, lj)
# print(grid)
for i in range(n):
for j in range(m):
if grid[i][j] == "Y":
grid[i][j] = "."
elif grid[i][j] == ".":
grid[i][j] = "X"
for row in grid:
print("".join(row))
# Function to test my code
def test():
pass
input_test()
# test()
``` | instruction | 0 | 72,840 | 15 | 145,680 |
Yes | output | 1 | 72,840 | 15 | 145,681 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Pavel loves grid mazes. A grid maze is an n Γ m rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side.
Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any other one. Pavel doesn't like it when his maze has too little walls. He wants to turn exactly k empty cells into walls so that all the remaining cells still formed a connected area. Help him.
Input
The first line contains three integers n, m, k (1 β€ n, m β€ 500, 0 β€ k < s), where n and m are the maze's height and width, correspondingly, k is the number of walls Pavel wants to add and letter s represents the number of empty cells in the original maze.
Each of the next n lines contains m characters. They describe the original maze. If a character on a line equals ".", then the corresponding cell is empty and if the character equals "#", then the cell is a wall.
Output
Print n lines containing m characters each: the new maze that fits Pavel's requirements. Mark the empty cells that you transformed into walls as "X", the other cells must be left without changes (that is, "." and "#").
It is guaranteed that a solution exists. If there are multiple solutions you can output any of them.
Examples
Input
3 4 2
#..#
..#.
#...
Output
#.X#
X.#.
#...
Input
5 4 5
#...
#.#.
.#..
...#
.#.#
Output
#XXX
#X#.
X#..
...#
.#.#
Submitted Solution:
```
# Description of the problem can be found at http://codeforces.com/problemset/problem/377/A
n, m, k = map(int, input().split())
t = [input().replace('.', 'X') for i in range(n)]
k = n * m - k - sum(i.count('#') for i in t)
t = [list(i) for i in t]
i, p = 0, []
while k:
if 'X' in t[i]:
j = t[i].index('X')
t[i][j], p = '.', [(i, j)]
k -= 1
break
i += 1
while k:
x, y = p.pop()
for i, j in ((x, y - 1), (x, y + 1), (x - 1, y), (x + 1, y)):
if i < 0 or j < 0: continue
if i < n and j < m and t[i][j] == 'X':
t[i][j] = '.'
p.append((i, j))
k -= 1
if k == 0: break
for i in range(n): t[i] = ''.join(t[i])
print("\n".join(t))
``` | instruction | 0 | 72,841 | 15 | 145,682 |
Yes | output | 1 | 72,841 | 15 | 145,683 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Pavel loves grid mazes. A grid maze is an n Γ m rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side.
Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any other one. Pavel doesn't like it when his maze has too little walls. He wants to turn exactly k empty cells into walls so that all the remaining cells still formed a connected area. Help him.
Input
The first line contains three integers n, m, k (1 β€ n, m β€ 500, 0 β€ k < s), where n and m are the maze's height and width, correspondingly, k is the number of walls Pavel wants to add and letter s represents the number of empty cells in the original maze.
Each of the next n lines contains m characters. They describe the original maze. If a character on a line equals ".", then the corresponding cell is empty and if the character equals "#", then the cell is a wall.
Output
Print n lines containing m characters each: the new maze that fits Pavel's requirements. Mark the empty cells that you transformed into walls as "X", the other cells must be left without changes (that is, "." and "#").
It is guaranteed that a solution exists. If there are multiple solutions you can output any of them.
Examples
Input
3 4 2
#..#
..#.
#...
Output
#.X#
X.#.
#...
Input
5 4 5
#...
#.#.
.#..
...#
.#.#
Output
#XXX
#X#.
X#..
...#
.#.#
Submitted Solution:
```
from sys import stdin
from collections import *
def arr_inp(n):
if n == 1:
return [int(x) for x in stdin.readline().split()]
elif n == 2:
return [float(x) for x in stdin.readline().split()]
else:
return list(stdin.readline()[:-1])
def valid(i, j):
global n, m
return i > -1 and i < n and j > -1 and j < m
dx, dy = [-1, 0, 1, 0], [0, 1, 0, -1]
def print_maze():
for i in range(n):
print(*maze[i], sep='')
def bfs_util(i, j):
queue, visit, q2 = deque([[i, j]]), defaultdict(int, {(i, j): 1}), deque([[i, j]])
while queue:
# dequeue parent vertix
s = queue.popleft()
# enqueue child vertices
for i in range(4):
ni, nj = s[0] + dx[i], s[1] + dy[i]
if valid(ni, nj) and not visit[ni, nj] and maze[ni][nj] != '#':
queue.append([ni, nj])
q2.append([ni, nj])
visit[ni, nj] = 1
for i in range(k):
ix1, ix2 = q2.pop()
maze[ix1][ix2] = 'X'
print_maze()
n, m, k = arr_inp(1)
maze = [arr_inp(3) for i in range(n)]
if k == 0:
print_maze()
else:
for i in range(n):
try:
ix = maze[i].index('.')
if ix != -1:
bfs_util(i, ix)
break
except:
continue
``` | instruction | 0 | 72,842 | 15 | 145,684 |
Yes | output | 1 | 72,842 | 15 | 145,685 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Pavel loves grid mazes. A grid maze is an n Γ m rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side.
Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any other one. Pavel doesn't like it when his maze has too little walls. He wants to turn exactly k empty cells into walls so that all the remaining cells still formed a connected area. Help him.
Input
The first line contains three integers n, m, k (1 β€ n, m β€ 500, 0 β€ k < s), where n and m are the maze's height and width, correspondingly, k is the number of walls Pavel wants to add and letter s represents the number of empty cells in the original maze.
Each of the next n lines contains m characters. They describe the original maze. If a character on a line equals ".", then the corresponding cell is empty and if the character equals "#", then the cell is a wall.
Output
Print n lines containing m characters each: the new maze that fits Pavel's requirements. Mark the empty cells that you transformed into walls as "X", the other cells must be left without changes (that is, "." and "#").
It is guaranteed that a solution exists. If there are multiple solutions you can output any of them.
Examples
Input
3 4 2
#..#
..#.
#...
Output
#.X#
X.#.
#...
Input
5 4 5
#...
#.#.
.#..
...#
.#.#
Output
#XXX
#X#.
X#..
...#
.#.#
Submitted Solution:
```
class Solution:
def __init__(self, grid, n, m, k):
self.grid = grid
self.n = n
self.m = m
self.k = k
self.neighbors = [(-1, 0), (1, 0), (0, -1), (0, 1)]
self.visited = [[False] * m for _ in range(n)]
def solve(self):
free_cells = 0
for row in range(self.n):
for col in range(self.m):
if self.grid[row][col] == '.':
free_cells += 1
start = row, col
self.num2visit = free_cells - self.k
self.bfs(*start)
for row in range(self.n):
for col in range(self.m):
if not self.visited[row][col] and self.grid[row][col] == '.':
self.grid[row][col] = 'X'
ans = []
for row in self.grid:
ans.append(''.join(row))
return '\n'.join(ans)
def bfs(self, row, col):
queue = [(row, col)]
while queue:
x, y = queue.pop()
self.visited[x][y] = True
self.num2visit -= 1
new_queue = []
for dr, dc in self.neighbors:
r = x + dr
c = y + dc
if 0 <= r < self.n and 0 <= c < self.m and self.grid[r][c] == '.':
if not self.visited[r][c]:
new_queue.append((r, c))
queue += new_queue
if self.num2visit == 0:
return
def main():
n, m, k = map(int, input().split())
grid = []
for _ in range(n):
grid.append(list(input()))
sol = Solution(grid, n, m, k)
ans = sol.solve()
print(ans)
if __name__ == "__main__":
main()
``` | instruction | 0 | 72,843 | 15 | 145,686 |
No | output | 1 | 72,843 | 15 | 145,687 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Pavel loves grid mazes. A grid maze is an n Γ m rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side.
Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any other one. Pavel doesn't like it when his maze has too little walls. He wants to turn exactly k empty cells into walls so that all the remaining cells still formed a connected area. Help him.
Input
The first line contains three integers n, m, k (1 β€ n, m β€ 500, 0 β€ k < s), where n and m are the maze's height and width, correspondingly, k is the number of walls Pavel wants to add and letter s represents the number of empty cells in the original maze.
Each of the next n lines contains m characters. They describe the original maze. If a character on a line equals ".", then the corresponding cell is empty and if the character equals "#", then the cell is a wall.
Output
Print n lines containing m characters each: the new maze that fits Pavel's requirements. Mark the empty cells that you transformed into walls as "X", the other cells must be left without changes (that is, "." and "#").
It is guaranteed that a solution exists. If there are multiple solutions you can output any of them.
Examples
Input
3 4 2
#..#
..#.
#...
Output
#.X#
X.#.
#...
Input
5 4 5
#...
#.#.
.#..
...#
.#.#
Output
#XXX
#X#.
X#..
...#
.#.#
Submitted Solution:
```
class Solution:
def __init__(self, grid, n, m, k):
self.grid = grid
self.n = n
self.m = m
self.k = k
self.neighbors = [(-1, 0), (1, 0), (0, -1), (0, 1)]
def solve(self):
while self.k > 0:
self.visited = [[False] * self.m for _ in range(self.n)]
self._solve()
ans = []
for row in self.grid:
ans.append(''.join(row))
return '\n'.join(ans)
def _solve(self):
for row in range(self.n):
for col in range(self.m):
if self.grid[row][col] == '.':
self.dfs(row, col)
return
return
def dfs(self, row, col):
self.visited[row][col] = True
if self.k == 0:
return
num_neighbors = 0
for dr, dc in self.neighbors:
r = row + dr
c = col + dc
if 0 <= r < self.n and 0 <= c < self.m:
if self.grid[r][c] == '.':
num_neighbors += 1
if num_neighbors <= 1:
self.grid[row][col] = 'X'
self.k -= 1
for dr, dc in self.neighbors:
r = row + dr
c = col + dc
if 0 <= r < self.n and 0 <= c < self.m:
if not self.visited[r][c]:
self.dfs(r, c)
def main():
n, m, k = map(int, input().split())
grid = []
for _ in range(n):
grid.append(list(input()))
sol = Solution(grid, n, m, k)
ans = sol.solve()
print(ans)
if __name__ == "__main__":
main()
``` | instruction | 0 | 72,844 | 15 | 145,688 |
No | output | 1 | 72,844 | 15 | 145,689 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Pavel loves grid mazes. A grid maze is an n Γ m rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side.
Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any other one. Pavel doesn't like it when his maze has too little walls. He wants to turn exactly k empty cells into walls so that all the remaining cells still formed a connected area. Help him.
Input
The first line contains three integers n, m, k (1 β€ n, m β€ 500, 0 β€ k < s), where n and m are the maze's height and width, correspondingly, k is the number of walls Pavel wants to add and letter s represents the number of empty cells in the original maze.
Each of the next n lines contains m characters. They describe the original maze. If a character on a line equals ".", then the corresponding cell is empty and if the character equals "#", then the cell is a wall.
Output
Print n lines containing m characters each: the new maze that fits Pavel's requirements. Mark the empty cells that you transformed into walls as "X", the other cells must be left without changes (that is, "." and "#").
It is guaranteed that a solution exists. If there are multiple solutions you can output any of them.
Examples
Input
3 4 2
#..#
..#.
#...
Output
#.X#
X.#.
#...
Input
5 4 5
#...
#.#.
.#..
...#
.#.#
Output
#XXX
#X#.
X#..
...#
.#.#
Submitted Solution:
```
n,m,k=[int(x) for x in input().split()]
maze=[]
for z in range(n):
arr=list(input())
maze.append(arr)
s,cnt,first=0,0,[]
for i in range(n):
for j in range(m):
if maze[i][j]==".":
s+=1
if len(first)==0:
first.append(i)
first.append(j)
def DFS(i,j):
global n,m,cnt,s,k
if i<0 or j<0 or i>=n or j>=m:
return
if maze[i][j]=="#" :
return
if cnt>=s-k:
return
cnt+=1
maze[i][j]="Y"
DFS(i+1,j)
DFS(i,j+1)
DFS(i-1,j)
DFS(i,j-1)
DFS(first[0],first[1])
for i in range(n):
for j in range(m):
if maze[i][j]==".":
maze[i][j]="X"
elif maze[i][j]=='Y':
maze[i][j]="."
for i in range(n):
s=""
for j in range(m):
s=s+maze[i][j]
print(s)
``` | instruction | 0 | 72,845 | 15 | 145,690 |
No | output | 1 | 72,845 | 15 | 145,691 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Pavel loves grid mazes. A grid maze is an n Γ m rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side.
Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any other one. Pavel doesn't like it when his maze has too little walls. He wants to turn exactly k empty cells into walls so that all the remaining cells still formed a connected area. Help him.
Input
The first line contains three integers n, m, k (1 β€ n, m β€ 500, 0 β€ k < s), where n and m are the maze's height and width, correspondingly, k is the number of walls Pavel wants to add and letter s represents the number of empty cells in the original maze.
Each of the next n lines contains m characters. They describe the original maze. If a character on a line equals ".", then the corresponding cell is empty and if the character equals "#", then the cell is a wall.
Output
Print n lines containing m characters each: the new maze that fits Pavel's requirements. Mark the empty cells that you transformed into walls as "X", the other cells must be left without changes (that is, "." and "#").
It is guaranteed that a solution exists. If there are multiple solutions you can output any of them.
Examples
Input
3 4 2
#..#
..#.
#...
Output
#.X#
X.#.
#...
Input
5 4 5
#...
#.#.
.#..
...#
.#.#
Output
#XXX
#X#.
X#..
...#
.#.#
Submitted Solution:
```
import sys
sys.setrecursionlimit(100000)
class Solution:
def __init__(self, grid, n, m, k):
self.grid = grid
self.n = n
self.m = m
self.k = k
self.neighbors = [(-1, 0), (1, 0), (0, -1), (0, 1)]
def solve(self):
while self.k > 0:
self.visited = [[False] * self.m for _ in range(self.n)]
self._solve()
ans = []
for row in self.grid:
ans.append(''.join(row))
return '\n'.join(ans)
def _solve(self):
for row in range(self.n):
for col in range(self.m):
if self.grid[row][col] == '.':
self.bfs(row, col)
return
return
def bfs(self, row, col):
queue = [(row, col)]
while queue:
x, y = queue.pop()
if self.visited[x][y]:
return
else:
self.visited[x][y] = True
new_queue = []
for dr, dc in self.neighbors:
r = x + dr
c = y + dc
if 0 <= r < self.n and 0 <= c < self.m and self.grid[r][c] == '.':
if not self.visited[r][c]:
new_queue.append((r, c))
if len(new_queue) == 0:
self.grid[x][y] = 'X'
self.k -= 1
else:
queue += new_queue
def main():
n, m, k = map(int, input().split())
grid = []
for _ in range(n):
grid.append(list(input()))
sol = Solution(grid, n, m, k)
ans = sol.solve()
print(ans)
if __name__ == "__main__":
main()
``` | instruction | 0 | 72,846 | 15 | 145,692 |
No | output | 1 | 72,846 | 15 | 145,693 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Finally Fox Ciel arrived in front of her castle!
She have to type a password to enter her castle. An input device attached to her castle is a bit unusual.
The input device is a 1 Γ n rectangle divided into n square panels. They are numbered 1 to n from left to right. Each panel has a state either ON or OFF. Initially all panels are in the OFF state. She can enter her castle if and only if x1-th, x2-th, ..., xk-th panels are in the ON state and other panels are in the OFF state.
She is given an array a1, ..., al. In each move, she can perform the following operation: choose an index i (1 β€ i β€ l), choose consecutive ai panels, and flip the states of those panels (i.e. ON β OFF, OFF β ON).
Unfortunately she forgets how to type the password with only above operations. Determine the minimal number of operations required to enter her castle.
Input
The first line contains three integers n, k and l (1 β€ n β€ 10000, 1 β€ k β€ 10, 1 β€ l β€ 100), separated by single spaces.
The second line contains k integers x1, ..., xk (1 β€ x1 < x2 < ... < xk β€ n), separated by single spaces.
The third line contains l integers a1, ..., al (1 β€ ai β€ n), separated by single spaces. It is possible that some elements of the array ai are equal value.
Output
Print the minimal number of moves required to type the password. If it's impossible, print -1.
Examples
Input
10 8 2
1 2 3 5 6 7 8 9
3 5
Output
2
Input
3 2 1
1 2
3
Output
-1
Note
One possible way to type the password in the first example is following: In the first move, choose 1st, 2nd, 3rd panels and flip those panels. In the second move, choose 5th, 6th, 7th, 8th, 9th panels and flip those panels.
Submitted Solution:
```
from collections import Counter
ans=float('inf')
def recur(b,pos,cost):
global ans
# print(b,pos,cost)
t=list(b)
if pos==n-1:
ans=min(ans,cost+(1 if t[pos]==1 else 0))
elif t[pos]==0:
recur(b,pos+1,cost)
else:
t[pos]=0
for d in al:
if pos+d<n:
t[pos+d]^=1
recur(tuple(t),pos+1,cost+1)
t[pos+d]^=1
n,k,l=map(int,input().split())
arr=list(map(int,input().split()))
al=list(map(int,input().split() ))
b=[0]*(n+1)
for i in range(k):
b[arr[i]]=1
# print(b)
for j in range(n):
if b[j]!=b[j+1]:
b[j]=1
else:
b[j]=0
# print(b)
recur(tuple(b),0,0)
if ans==float('inf'):
print(-1)
else:
print(ans)
``` | instruction | 0 | 72,998 | 15 | 145,996 |
No | output | 1 | 72,998 | 15 | 145,997 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.
Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.
Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?
Input
The first line contains two integers n, m (1 β€ n, m β€ 2000) β the number of rows and the number columns in the labyrinth respectively.
The second line contains two integers r, c (1 β€ r β€ n, 1 β€ c β€ m) β index of the row and index of the column that define the starting cell.
The third line contains two integers x, y (0 β€ x, y β€ 109) β the maximum allowed number of movements to the left and to the right respectively.
The next n lines describe the labyrinth. Each of them has length of m and consists only of symbols '.' and '*'. The j-th character of the i-th line corresponds to the cell of labyrinth at row i and column j. Symbol '.' denotes the free cell, while symbol '*' denotes the cell with an obstacle.
It is guaranteed, that the starting cell contains no obstacles.
Output
Print exactly one integer β the number of cells in the labyrinth, which are reachable from starting cell, including the starting cell itself.
Examples
Input
4 5
3 2
1 2
.....
.***.
...**
*....
Output
10
Input
4 4
2 2
0 1
....
..*.
....
....
Output
7
Note
Cells, reachable in the corresponding example, are marked with '+'.
First example:
+++..
+***.
+++**
*+++.
Second example:
.++.
.+*.
.++.
.++.
| instruction | 0 | 73,319 | 15 | 146,638 |
Tags: graphs, shortest paths
Correct Solution:
```
'''input
4 5
3 2
1 2
.....
.***.
...**
*....
3 5
3 2
1 2
.....
.***.
...**
4 4
2 2
0 1
....
..*.
....
....
'''
from collections import deque
n, m = map(int, input().split())
sx, sy = map(int, input().split())
tl, tr = map(int, input().split())
g = [input() for i in range(n)]
sx -= 1
sy -= 1
dis = [[-1 for j in range(m)] for i in range(n)]
q = deque()
def go(x, y, s, left=False):
if 0 <= x < n and 0 <= y < m:
if s + y - sy > tr * 2:
return
if s - y + sy > tl * 2:
return
if g[x][y] == '*':
return
if dis[x][y] == -1:
dis[x][y] = s
if left:
q.appendleft((x, y))
else:
q.append((x, y));
go(sx, sy, 0)
ans = 0
while q:
x, y = q.popleft()
s = dis[x][y]
# print(x, y)
ans += 1
go(x - 1, y, s, left=True)
go(x + 1, y, s, left=True)
go(x, y - 1, s + 1)
go(x, y + 1, s + 1)
print(ans)
``` | output | 1 | 73,319 | 15 | 146,639 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.
Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.
Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?
Input
The first line contains two integers n, m (1 β€ n, m β€ 2000) β the number of rows and the number columns in the labyrinth respectively.
The second line contains two integers r, c (1 β€ r β€ n, 1 β€ c β€ m) β index of the row and index of the column that define the starting cell.
The third line contains two integers x, y (0 β€ x, y β€ 109) β the maximum allowed number of movements to the left and to the right respectively.
The next n lines describe the labyrinth. Each of them has length of m and consists only of symbols '.' and '*'. The j-th character of the i-th line corresponds to the cell of labyrinth at row i and column j. Symbol '.' denotes the free cell, while symbol '*' denotes the cell with an obstacle.
It is guaranteed, that the starting cell contains no obstacles.
Output
Print exactly one integer β the number of cells in the labyrinth, which are reachable from starting cell, including the starting cell itself.
Examples
Input
4 5
3 2
1 2
.....
.***.
...**
*....
Output
10
Input
4 4
2 2
0 1
....
..*.
....
....
Output
7
Note
Cells, reachable in the corresponding example, are marked with '+'.
First example:
+++..
+***.
+++**
*+++.
Second example:
.++.
.+*.
.++.
.++.
| instruction | 0 | 73,320 | 15 | 146,640 |
Tags: graphs, shortest paths
Correct Solution:
```
input = __import__('sys').stdin.readline
print = __import__('sys').stdout.write
from collections import deque
n, m = map(int, input().split())
sx, sy = map(int, input().split())
l, r = map(int, input().split())
sx-=1
sy-=1
lab = [input() for _ in range(n)]
visited = [[-1 for j in range(m)] for i in range(n)]
q = deque()
def go(x, y, s, lf=False):
if 0<=x<n and 0<=y<m and lab[x][y] == '.' and visited[x][y] == -1:
visited[x][y] = s
if lf:
q.appendleft((x, y))
else:
q.append((x,y))
ans = 0
go(sx, sy, 0)
while q:
n_x, n_y = q.popleft()
s = visited[n_x][n_y]
ans += s+ n_y - sy <= r*2 and s-n_y + sy <= l*2
go(n_x-1, n_y, s, True)
go(n_x +1, n_y, s , True)
go(n_x, n_y -1, s+1)
go (n_x, n_y + 1, s + 1)
print(str(ans))
``` | output | 1 | 73,320 | 15 | 146,641 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.
Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.
Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?
Input
The first line contains two integers n, m (1 β€ n, m β€ 2000) β the number of rows and the number columns in the labyrinth respectively.
The second line contains two integers r, c (1 β€ r β€ n, 1 β€ c β€ m) β index of the row and index of the column that define the starting cell.
The third line contains two integers x, y (0 β€ x, y β€ 109) β the maximum allowed number of movements to the left and to the right respectively.
The next n lines describe the labyrinth. Each of them has length of m and consists only of symbols '.' and '*'. The j-th character of the i-th line corresponds to the cell of labyrinth at row i and column j. Symbol '.' denotes the free cell, while symbol '*' denotes the cell with an obstacle.
It is guaranteed, that the starting cell contains no obstacles.
Output
Print exactly one integer β the number of cells in the labyrinth, which are reachable from starting cell, including the starting cell itself.
Examples
Input
4 5
3 2
1 2
.....
.***.
...**
*....
Output
10
Input
4 4
2 2
0 1
....
..*.
....
....
Output
7
Note
Cells, reachable in the corresponding example, are marked with '+'.
First example:
+++..
+***.
+++**
*+++.
Second example:
.++.
.+*.
.++.
.++.
| instruction | 0 | 73,321 | 15 | 146,642 |
Tags: graphs, shortest paths
Correct Solution:
```
import collections
n,m = map(int,input().split())
r,c = map(int,input().split())
x,y = map(int,input().split())
arr = []
for i in range(n):
arr.append(input())
que = collections.deque([(r-1,c-1)])
dist = [[float("inf")]*m for i in range(n)]
dist[r-1][c-1] = 0
while que:
v = que.popleft()
if v[0]>0 and arr[v[0]-1][v[1]] != "*" and dist[v[0]-1][v[1]] > dist[v[0]][v[1]]:
dist[v[0]-1][v[1]] = dist[v[0]][v[1]]
que.appendleft((v[0]-1,v[1]))
if v[0]<n-1 and arr[v[0]+1][v[1]] != "*" and dist[v[0]+1][v[1]] > dist[v[0]][v[1]]:
dist[v[0]+1][v[1]] = dist[v[0]][v[1]]
que.appendleft((v[0]+1,v[1]))
if v[1]<m-1 and arr[v[0]][v[1]+1] != "*" and dist[v[0]][v[1]+1] > dist[v[0]][v[1]]:
dist[v[0]][v[1]+1] = dist[v[0]][v[1]]
que.appendleft((v[0],v[1]+1))
if v[1]>0 and arr[v[0]][v[1]-1] != "*" and dist[v[0]][v[1]-1] > dist[v[0]][v[1]]+1:
dist[v[0]][v[1]-1] = dist[v[0]][v[1]]+1
que.append((v[0],v[1]-1))
count = 0
for i in range(n):
for e in range(m):
if dist[i][e] <= x and e-(c-1)+dist[i][e] <= y:
#print(i,e)
count+=1
print(count)
``` | output | 1 | 73,321 | 15 | 146,643 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.