题目链接戳这
描述:网格上有一些电源节点,你需要按照顺序遍历这些节点,输出每个节点以及它的右邻点和下邻点。
关键词:二维数组,双循环
实现官方提示:您必须从字符串中检测特殊字符。您还必须将输入值存储到网格中以进行探索。您必须遍历网格中的所有元素(当然使用双循环),然后从这些点再次迭代网格的某些元素。解决这个难题使您了解嵌套循环的概念。
循环遍历每个网格坐标,如果该坐标为空(即’.'),则跳过;否则从该点出发寻找当前点的右邻点和下邻点 并记录输出。
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] == ".":
continue
rx = ry = bx = by = -1
for tx in range(x + 1, width):
if(lines[y][tx] == '0'):
rx = tx
ry = y
break
for ty in range(y+1, height):
if(lines[ty][x] == '0'):
bx = x
by = ty
break
print("{0} {1} {2} {3} {4} {5}".format( x, y, rx, ry, bx, by))
总结
嵌套循环总是捋不清。。而且感觉应该还是有一定的优化空间的。



