我应该在哪里放置计数变量?

时间:2015-03-15 18:38:18

标签: java recursion

编写一个递归方法,计算网格上的生物数量。生物被定义为1的连续集合(水平和垂直连接)。我设法接近连接代码,但我陷入了应该放置count变量的位置 例如: 如果输入是

0 0 0 0 1
0 1 1 1 0
1 0 0 0 0
0 0 0 0 0
0 0 0 0 0

输出应为

0 0 0 0 1
0 2 2 2 0
3 0 0 0 0
0 0 0 0 0
0 0 0 0 0

代码:

public static void clearpic(int[][] a, int row, int col, int SIZE) {
    if ((0 <= row) && (row < SIZE) && (0 <= col) && (col < SIZE) && a[row][col] == 1) {
        a[row][col] = count;
        clearpic(a, row + 1, col, SIZE);
        clearpic(a, row, col + 1, SIZE);
        clearpic(a, row - 1, col, SIZE);
        clearpic(a, row, col - 1, SIZE);
    }
}

public static void print(int[][] a, int r, int c) {
    for (int i = 0; i < a.length; i++) {
        for (int j = 0; j < a[i].length; j++) {
            clearpic(a, i, j, a.length);
        }
        count++;
    }
    for (int i = 0; i < a.length; i++) {
        for (int j = 0; j < a[i].length; j++) {
            System.out.print(a[i][j]);
        }
        System.out.print("\n");
    }
}

1 个答案:

答案 0 :(得分:0)

您需要将计数作为形式参数传递给递归函数。

public static void clearpic(int[][] a, int row, int col, int SIZE, int count) {
    if ((0 <= row) && (row < SIZE) && (0 <= col) && (col < SIZE) && a[row][col] == 1) {
        a[row][col] = count;
        clearpic(a, row + 1, col, SIZE, count);
        clearpic(a, row, col + 1, SIZE, count);
        clearpic(a, row - 1, col, SIZE, count);
        clearpic(a, row, col - 1, SIZE, count);
    }
}

以下代码应足以满足您提到的测试用例。

public static void print(int[][] a, int r, int c) {
    int count = 1;
    for (int i = 0; i < a.length; i++) {
        for (int j = 0; j < a[i].length; j++) {
            clearpic(a, i, j, a.length, count);
        }
        count++;
    }
    for (int i = 0; i < a.length; i++) {
        for (int j = 0; j < a[i].length; j++) {
            System.out.print(a[i][j]);
        }
        System.out.print("\n");
    }
}

希望这有帮助。