數字迷宮

/************************************************
        Question: http://weibo.com/1915548291/z4eTPtAnv
************************************************/

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

#define MAX_STEP_SIZE 16 //so that we can get the result quickly

int l_cw(int n)
{
        return (n/2 + 7);
}

int l_ccw(int n)
{
        return (n + 7)/2;
}

int r_cw(int n)
{
        return (n * 3 - 5);
}

int r_ccw(int n)
{
        return (n - 5) * 3;
}

int l_cw_hf(int n)
{
        return (n + 7);
}

int l_ccw_hf(int n)
{
        return (n/2);
}

int r_cw_hf(int n)
{
        return (n * 3);
}

int r_ccw_hf(int n)
{
        return (n -5);
}
int maze_hub(int n, int step);
int disp_path(int step);

typedef int (*fun_t)(int n);

fun_t jump_table[8] = {
        l_cw,
        r_cw,
        r_ccw,
        l_ccw,

        l_cw_hf,
        r_cw_hf,
        r_ccw_hf,
        l_ccw_hf
};

char *operate_str[8] = {
        "/2 +7",
        "*2 -5",
        "-5 *3",
        "+7 /2",

        "+7",
        "*3",
        "-5",
        "/2"
};

int direct[MAX_STEP_SIZE] = {0};

int main(int argc, char *argv[])
{

        int step = 1;
        int val;

        direct[1] = 0;
        val = maze_hub(2011 + 7, 1);
        direct[1] = 3;
        val = maze_hub(2011/2, 1);
        printf("\n========END==========\n");
        return 0;
}

int maze_hub(int n, int step)
{
        step++;
        if(step >= MAX_STEP_SIZE )
        {
                return -1;
        }
        int pre_direct = direct[step - 1];
        if(pre_direct != 1)
        {
                if(n - 5 == 2012)
                {
                        direct[step] = 6;
                        disp_path(step);
                        return 2012;
                }
        }
        if(pre_direct != 2)
        {
                if(n * 3 == 2012)
                {
                        direct[step] = 5;
                        disp_path(step);
                        return 2012;
                }
        }
        int i, val;
        for(i = 0; i < 4; i++)
        {
                if(i + pre_direct != 3)
                {
                        direct[step] = i;
                        val = maze_hub(jump_table[i](n), step);
                }
        }


        return val;
}

int disp_path(int step)
{
        int i, offset, val = 2011;
        printf("\nStart num\t\t=%d\n", val);
        for(i = 1; i <= step; i++)
        {
                if(i == 1)
                {
                        offset = 4;
                }
                else
                {
                        offset = 0;
                }
                val = jump_table[direct[i] + offset](val);
                printf("Step%3d:\t%5s\t=%d\n", i, operate_str[direct[i] + offset], val);
        }
        printf("--------------------------------------\n");
        return 0;
        //exit(0);
}
相關文章
相關標籤/搜索