【python】There is no Spoon- Episode 1
CodingGames 之 There is no Spoon- Episode 1
题目链接戳这
描述:网格上有一些电源节点,你需要按照顺序遍历这些节点,输出每个节点以及它的右邻点和下邻点。
关键词:二维数组,双循环
官方提示:您必须从字符串中检测特殊字符。您还必须将输入值存储到网格中以进行探索。您必须遍历网格中的所有元素(当然使用双循环),然后从这些点再次迭代网格的某些元素。解决这个难题使您了解嵌套循环的概念。
实现
循环遍历每个网格坐标,如果该坐标为空(即’.'),则跳过;否则从该点出发寻找当前点的右邻点和下邻点 并记录输出。
import sys
import math# Don't let the machines win. You are humanity's last hope...
lines = []
width = int(input()) # the number of cells on the X axis
height = int(input()) # the number of cells on the Y axis
for i in range(height):line = input() # width characters, each either 0 or .lines.append(list(line))# Write an action using print
# To debug: print("Debug messages...", file=sys.stderr, flush=True)
for y in range(height):for x in range(width):if lines[y][x] == ".":continuerx = ry = bx = by = -1for tx in range(x + 1, width):if(lines[y][tx] == '0'):rx = txry = ybreakfor ty in range(y+1, height):if(lines[ty][x] == '0'):bx = xby = tybreakprint("{0} {1} {2} {3} {4} {5}".format( x, y, rx, ry, bx, by))
总结
嵌套循环总是捋不清。。而且感觉应该还是有一定的优化空间的。
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
