我应该在递归中使用全局变量吗

问题描述 投票:0回答:1

我用 C 创建了一个函数,使用递归找到三角形迷宫的最短路径。我在函数中使用了 2 个全局变量,我想将其删除,因为我知道不应使用全局变量。

变量

moves
,我可以作为参数传递,但我不知道这样压垮堆栈是否是糟糕的内存管理。 另一个全局变量
foundExit
不能作为参数,所以我不知道如何摆脱它。

所以我的问题是在递归的情况下是否应该使用全局变量。

请注意,数组中的每个数字都是 3 位数字,其中 1 代表墙,0 代表空墙。 001 是左墙,010 是右墙,100 是底/上墙。例如 111 代表三角形及其所有的墙。

我们的迷宫图片保存在单元格中:

image of our maze

简化代码:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

typedef struct {
    int rows;
    int cols;
    unsigned char *cells;
} Map;

void NegateEntraceBit(Map *map, unsigned char r, unsigned char c) {
    char whichWall;
    if (c == 0) { // From left.
        whichWall = 0;
    }
    else if (c == map->cols - 1) { // From right.
        whichWall = 1;
    }
    else if (r == 0) { // From up.
        whichWall = 2;
    }
    else if (r == map->rows - 1) { // From down.
        whichWall = 2;
    }

    //Inverting entrace bit.
    map->cells[map->cols * r + c] ^= (1 << whichWall); 
}

char InvertDirection(char direction) {
    if (direction == 0) {
        return 1;
    }
    else if (direction == 1) {
        return 0;
    } else {
        return 2;
    }
}

char moves[2][3][2] = {
    {{0,-1}, {0,1}, {-1,0}},
    {{0,-1}, {0,1}, {1,0}}
};

bool foundExit = false;

void shortestPath(Map map, int r, int c, char direction) {
/* 
         (r+c) % 2 == 1:        (r+c) % 2 == 0:
                ^               _________
              ╱   ╲             ╲   2   ╱
           0 ╱     ╲ 1         0 ╲     ╱ 1
            ╱_______╲             ╲   ╱
                2                   v
*/
    
    // Going in the direction if its the only way (triangle has value 0b100).
    while (map.cells[map.cols * r + c] == 3) {
        r += moves[(r+c) & 1][direction][0];
        c += moves[(r+c) & 1][direction][1];

        // This validating is performed when we go in 1 line to the exit.
        if (r < 0 || r >= map.rows || c < 0 || c >= map.cols) { // Outside position
            foundExit = true;
            return;
        }
    }

    // This validating is performed when a new instance is called.
    if (r < 0 || r >= map.rows || c < 0 || c >= map.cols) { // Outside position
        foundExit = true;
        return;
    }

    // This validating is performed when the only other way is in inverted direction.
    if ((map.cells[map.cols * r + c] ^ (1 << InvertDirection(direction))) == 0b111) {
        return;
    }

    printf("%d,%d\n", r+1, c+1);

    // For any other direction
    for (char direc = 0; direc < 3; direc++) {
        // that is (available && not in inverted direction),
        if ( !(map.cells[map.cols * r + c] & (1 << direc)) && (direc != InvertDirection(direction))) {
            // we call new instance with new coordinates.
            shortestPath(map,
                         r + moves[(r+c) & 1][direc][0], 
                         c + moves[(r+c) & 1][direc][1], 
                         direc);
        } 
        // Stopping any other instance that would be called even when the exit is found.
        if (foundExit) {
            break;
        }            
    }
}

int main() {
    Map map;
    map.rows = 6;
    map.cols = 7; // Set to the number of columns in your data

    // Allocate memory for 1D array
    map.cells = malloc(sizeof(unsigned char) * (map.rows * map.cols));

    // Initialize the 1D array directly
    unsigned char initialData[] = {
        1, 4, 4, 2, 5, 0, 6,
        1, 4, 4, 0, 4, 0, 2,
        1, 0, 4, 0, 4, 6, 1,
        1, 2, 7, 1, 0, 4, 2,
        3, 1, 4, 2, 3, 1, 2,
        4, 2, 5, 0, 4, 2, 5
    };

    for (int i = 0; i < map.rows * map.cols; i++) {
        map.cells[i] = initialData[i];
    }
    int r = 6;
    int c = 1;

    int rows = r-1;
    int cols = c-1;

    // Closing entrace bit so its not the shortest path out.
    NegateEntraceBit(&map, rows, cols);
    //For every direction
    for (char direc = 0; direc < 3; direc++) {
        // That is available (0).
        if ( !(map.cells[map.cols * rows + cols] & (1 << direc)) ) {
            shortestPath(map, rows, cols, direc);
        }     
    }

    // Free allocated memory
    free(map.cells);

    return 0;
}
c variables recursion global
1个回答
0
投票

两个全局变量都在单个函数中访问

shortestPath()
,因此它们可以在该函数中声明为
static

static char moves[2][3][2] = {
    {{0,-1}, {0,1}, {-1,0}},
    {{0,-1}, {0,1}, {1,0}}
};

static bool foundExit = false;

在多个函数之间共享变量的其他情况下,请将所有这些函数和变量放在单独编译的源文件中,并声明变量和任何未外部引用的函数

static
,在这种情况下是一个链接说明符而不是如上所述的存储类说明符,并将范围限制为该翻译单元(因此不再是全局的)。

© www.soinside.com 2019 - 2024. All rights reserved.