避免二维数组中的边缘

时间:2017-11-17 01:43:24

标签: java arrays

任务是构建一个像这样的数组的程序:
                                                            #0 -1 0#
                                                            #0 0 -1#
                                                            #0 0 -1#
并用包含“-1”的边界单元格替换所有零。像这样:
          #1 -1 2#
          #1 3 -1#
          #0 2 -1#

我目前通过在数组中添加“缓冲区”来解决这个问题,以避免超出范围的异常。

public class ArrayTest {

    public static void main(String[] args) {

        Integer[][] fields = {  { 0, 0, 0, 0, 0 },
                            { 0, 0, -1, 0, 0 },
                            { 0, 0, 0, -1, 0 },
                            { 0, 0, 0, -1, 0 },
                            { 0, 0, 0, 0, 0 }};

        int pos_x = 1, pos_y = 1, t_x = 1, t_y = 1, sum = 0, maxy = fields[0].length-1, maxx = fields.length-1;

        System.out.println(fields[1][1] + " " + fields[1][2] + " " + fields[1][3]);
        System.out.println(fields[2][1] + " " + fields[2][2] + " " + fields[2][3]);
        System.out.println(fields[3][1] + " " + fields[3][2] + " " + fields[3][3]);

        // xloop
        for (pos_x = 1; pos_x < maxx; pos_x++) {
            // yloop
            for (pos_y = 1; pos_y < maxy; pos_y++) {

                if (fields[pos_x][pos_y] != -1) {

                    // t_x loop
                    for (t_x = pos_x - 1; t_x <= pos_x + 1; t_x++) {

                        // t_y loop
                        for (t_y = pos_y - 1; t_y <= pos_y + 1; t_y++) {
                            if ((fields[t_x][t_y] == -1)) {
                                sum += 1;
                            }

                        }
                    }
                    fields[pos_x][pos_y]=sum;
                    sum=0;
                }

            }
        }

        System.out.println(" ");
        System.out.println(fields[1][1] + " " + fields[1][2] + " " + fields[1][3]);
        System.out.println(fields[2][1] + " " + fields[2][2] + " " + fields[2][3]);
        System.out.println(fields[3][1] + " " + fields[3][2] + " " + fields[3][3]);

    }

}

然而,这对我来说似乎很粗糙,我更喜欢不改变原始阵列的解决方案。我尝试了一些东西,但到目前为止我没有解决它。任何指针都将受到高度赞赏!

0 个答案:

没有答案