// 方形遍历,只遍历方形的4条边 // cx,cy=中心点坐标 // r=半径,至少1 // 以r==2为例,seq == Default, 遍历顺序如下 // 9CEGA // 7 8 // 5 * 6 // 3 4 // 1BDF2 public static void SquareFor(int cx, int cy, int r, Action <int, int> f, SquareForSeq seq = SquareForSeq.Default, Func <bool> continueCondition = null) { if (r < 0 || (continueCondition != null && !continueCondition())) { return; } if (r == 0) { f(cx, cy); return; } if (seq == SquareForSeq.PerpendicularFirst) { f(cx - r, cy); // 左 f(cx + r, cy); // 右 f(cx, cy + r); // 上 f(cx, cy - r); // 下 // 左右(包括上下左右4个角落) For(cy - r, cy + r + 1, (_y) => { if (_y == cy) { return; } f(cx - r, _y); f(cx + r, _y); }, continueCondition); // 上下(不包括4个角落) For(cx - r + 1, cx + r, (_x) => { if (_x == cx) { return; } f(_x, cy - r); f(_x, cy + r); }, continueCondition); } else { // 左右(包括上下左右4个角落) For(cy - r, cy + r + 1, (_y) => { f(cx - r, _y); f(cx + r, _y); }, continueCondition); // 上下(不包括4个角落) For(cx - r + 1, cx + r, (_x) => { f(_x, cy - r); f(_x, cy + r); }, continueCondition); } }
public static void SquareFor2(int cx, int cy, int start_r, int end_r, Action <int, int> f, SquareForSeq seq = SquareForSeq.Default, Func <bool> continueCondition = null) { for (int r = start_r; r < end_r && (continueCondition == null || continueCondition()); r++) { SquareFor(cx, cy, r, f, seq, continueCondition); } }