一般情況:如何實現遍歷偏移並更高效地使用遍歷偏移?如何更好地實現遍歷(位)映射?
比方說,我們有一個位圖定義如下。我們如何從一個固定像素開始遍歷(在這種情況下收集)所有附近的像素 - 最終避免這8個if語句?
// The bitmap 1920x1080px
RGBColor[][] imageMatrix = new RGBColor[1920][1080];
// Collect all nearby pixels that are not white
ArrayList<RGBColor> neighboringPixels = new ArrayList<RGBColor>();
// Width-index of center pixel
int w = 50;
// Height-index of center pixel
int h = 50;
// Initializing offsets for a more elegant check-up...
int[][] offsets = { { -1, -1 }, { 0, -1 }, { 1, -1 },
{ 1, 0 }, { 1, 1 }, { 0, 1 }, { -1, 1 },
{ -1, 0 } };
// But this is what I came up with
// Get top-left pixel
if (!(w - 1 < 0 || w - 1 > 255 || h - 1 < 0 || h - 1 > 255)) {
neighboringPixels.add(imageMatrix[w - 1][h - 1]);
}
// Get top pixel
if (!(w < 0 || w > 255 || h - 1 < 0 || h - 1 > 255)) {
neighboringPixels.add(imageMatrix[w][h - 1]);
}
// Get top-right pixel
if (!(w + 1 < 0 || w + 1 > 255 || h - 1 < 0 || h - 1 > 255)) {
neighboringPixels.add(imageMatrix[w + 1][h - 1]);
}
// Get right pixel
if (!(w + 1 < 0 || w + 1 > 255 || h < 0 || h > 255)) {
neighboringPixels.add(imageMatrix[w + 1][h]);
}
// Get bottom-right pixel
if (!(w + 1 < 0 || w + 1 > 255 || h + 1 < 0 || h + 1 > 255)) {
neighboringPixels.add(imageMatrix[w + 1][h + 1]);
}
// Get bottom pixel
if (!(w < 0 || w > 255 || h + 1 < 0 || h + 1 > 255)) {
neighboringPixels.add(imageMatrix[w][h + 1]);
}
// Get bottom-left pixel
if (!(w - 1 < 0 || w - 1 > 255 || h + 1 < 0 || h + 1 > 255)) {
neighboringPixels.add(imageMatrix[w - 1][h + 1]);
}
// Get left pixel
if (!(w - 1 < 0 || w - 1 > 255 || h < 0 || h > 255)) {
neighboringPixels.add(imageMatrix[w - 1][h]);
}
定義「有效」?你的意思是速度或代碼行嗎? –
@Lashane我主要是指一行代碼。如果我們在三維空間中工作,必須有一種方法可以避免這8個if語句,甚至是26個if語句。 – JAR