有一个5*5坐标,每个坐标对应'green' 'red' 'blue' 'orange' 'purple' 5个字符串中的一个。 如(1 1 green) (1 2 purple) 我选定一个坐标,需要找到与它相邻且对应字符串相同的所有坐标。
我将坐标行和列分别扩充到边界,与选取的进行对比
但是这样比较范围至多只能扩展成以选取坐标为交叉中心的十字形区域
我想找到相邻且对应字符串相同的所有坐标
用队列进行广度搜索即可
你题目的解答代码如下:
mp = [
["R","B","P","G","R"],
["R","B","G","P","G"],
["R","P","G","R","B"],
["R","R","R","B","P"],
["P","R","R","B","P"]
]
x = int(input("请输入x坐标1-5:"))-1
y = int(input("请输入y坐标1-5:"))-1
dn = [(0,1),(0,-1),(1,0),(-1,0)]
qu = [(x,y)] #第一个坐标放到队列中
cv = mp[y][x]
mp[y][x] = " " #把mp中第一个坐标内容清空, 下次就不会重复判断了
print("所有坐标:")
while len(qu)>0: #判断队列为非空则循环
x,y = qu.pop(0) #从队列中取出队头坐标
print("x =",x+1,", y =",y+1)
for ux,uy in dn:
fx = x + ux
fy = y + uy
if 0<=fx<5 and 0<=fy<5 and mp[fy][fx]==cv:
qu.append((fx,fy)) #找到的坐标放到队列中
mp[fy][fx] = " " #把找到的坐标内容清空, 下次就不会重复判断了
#遍历之后的mp
print(*mp,sep="\n")
如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!
a = [["R","R","R","R","R"],["R","B","G","O","P"],["R","B","G","O","P"],["R","B","G","O","P"],["R","B","G","O","P"]]
get = input().split(",")
get = list(map(lambda x: int(x),get))
final = []
get[0] -= 1
get[1] -= 1
final.append(get)
b = []
check = []
ref = []
for i in range(0,5):
for j in range(0,5):
check = [i,j]
ref.append(check)
check =[]
c = 0
d = False
for i in final:
for x in range(0,i[0]):
check.append([i[0],x])
if a[i[0]][i[1]] == a[i[0]][x]:
b = [i[0],x]
final.append(b)
for x in range(i[0], len(a[i[0]])):
check.append([i[0],x])
if a[i[0]][i[1]] == a[i[0]][x]:
b = [i[0],x]
final.append(b)
for x in range(0, i[1]):
check.append([x,i[1]])
if a[i[0]][i[1]] == a[x][i[1]]:
b = [x,i[1]]
final.append(b)
for x in range(i[1], len(a[i[1]])):
check.append([x,i[1]])
if a[i[0]][i[1]] == a[x][i[1]]:
b = [x,i[1]]
final.append(b)
for y in check:
if y in ref:
c += 1
if c== 25:
d = True
break
c = 0
if d== True:
break
real = []
for i in range(0,len(final)):
for j in range(0,len(final[i])):
final[i][j] += 1
for i in final:
if i not in real:
real.append(i)
print(real)
花了我半天时间,一定要给个采纳,求求了
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!