程式語言 - LeetCode - C - 1926. Nearest Exit from Entrance in Maze



參考資訊:
https://www.cnblogs.com/cnoodle/p/16913967.html

題目:


解答:

#define MAX_SIZE 10000
 
int nearestExit(char **maze, int mazeSize, int *mazeColSize, int *entrance, int entranceSize)
{
    int r = 0;
    int i = 0;
    int j = 0;
    int st = 0;
    int ep = 0;
    int **q = NULL;
 
    q = calloc(MAX_SIZE, sizeof(int *));
    for (i = 0; i < MAX_SIZE; i++) {
        q[i] = calloc(2, sizeof(int));
    }
 
    st = 0;
    q[ep][0] = entrance[0];
    q[ep][1] = entrance[1];
    maze[q[ep][0]][q[ep][1]] = '+';
    ep += 1;
 
    r = 0;
    while ((ep - st) > 0) {
        int row = 0;
        int col = 0;
        int len = ep;
        int dir[] = { -1, 0, 1, 0, -1 };

        r += 1;
        for (i = st; i < len; i++) {
            for (j = 0; j < 4; j++) {
                col = q[i][0] + dir[j];
                row = q[i][1] + dir[j + 1];
 
                if ((row < 0) || (col < 0) || (row >= mazeColSize[0]) || (col >= mazeSize)) {
                    continue;
                }
                if (maze[col][row] == '+') {
                    continue;
                }
                if ((row == 0) || (col == 0) || (row == (mazeColSize[0] - 1)) || (col == (mazeSize - 1))) {
                    return r;
                }
 
                q[ep][0] = col;
                q[ep][1] = row;
                maze[q[ep][0]][q[ep][1]] = '+';
                ep += 1;
            }
            st += 1;
        }
    }
 
    return -1;
}