Esempio n. 1
0
/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int *preorderTraversal(struct TreeNode *root, int *returnSize) {
    int *r = NULL, sz = 0;
    Stack stack, *pstk = &stack;
    initStack(pstk);

    push(pstk, root);
    struct TreeNode *p;
    while (1) {
        pop(pstk, &p);
        if (p == NULL) {
            break;
        }
        push(pstk, p->right);
        push(pstk, p->left); // left first, when pop
        sz++;
        reallocM(&r, sizeof(int) * sz);
        r[sz - 1] = p->val;
    }

    deinitStack(pstk);
    *returnSize = sz;
    return r;
}
Esempio n. 2
0
File: main.c Progetto: vrjunior/maze
int main() {
    setlocale(LC_ALL, "Portuguese");
    int lin, col;
    Point pos;
    Stack *ways;
    BoolPos currentSituation;
    int i;

    FILE *arquivo;
    arquivo = fopen("labirinto.txt", "r");

    if(arquivo == NULL) {
        printf("Erro ao carregar o labirinto, arquivo não pode ser aberto.");
        return 0;
    }

    fscanf(arquivo, "%i %i", &lin, &col);
    printf("Labirinto %i x %i\n\n", lin, col);

    // Alocate +1 to acomodate the \0 at end of final line
    char (*maze)[col] = (char(*)[col]) malloc((sizeof(char)*lin*col) + 1);

    for(i=0; i<lin; i++) {
        fscanf(arquivo, "%s", maze[i]);
    }

    if (!searchEntry(lin, col, maze, &pos)) {
        printf("\nNão há entrada para esse labirinto, impossível continuar");
        return 0;
    }

    ways = createStack(lin * col);
    push(ways, pos);
    maze[pos.x][pos.y] = 'v';
    while(maze[pos.x][pos.y] != MAZE_OUT) {
        checkPositions(&currentSituation, &pos, lin, col, maze);

        if(maze[pos.x][pos.y] == MAZE_WAY) {
            maze[pos.x][pos.y] = 'v'; //Move
        }

        printf("\nTentativa: %i x %i", pos.x, pos.y);

        if(currentSituation.left == 0 && currentSituation.bottom == 0 && currentSituation.right == 0 && currentSituation.top == 0) {
            if (!pop(ways, &pos)) {
                printf("\nEntrada encontrada não leva para uma saída!\n");

                if(searchEntry(lin, col, maze, &pos)) {
                    printf("Nova entrada encontrada! Resolvendo...\n");
                    push(ways, pos);
                }
                else {
                    printf("\n\nNão foi possível encontrar o caminhos a(s) entrada(s) encontrada(s) não levam à uma saída!\n");
                    break;
                }
            }
        } else {
            push(ways, pos);
        }
    }

    printf("\n\nLabirinto descoberto com sucesso!\nO caminho é:\n\n");

    while(pop(ways, &pos) == TRUE) {
        printf("%iº passo: %i x %i\n", ways->topo +1, pos.x, pos.y);
    }

    deinitStack(ways);
    printf("\n\n");

    free(maze);
    fclose(arquivo);

    system("Pause");
    return 0;
}