本文共 2360 字,大约阅读时间需要 7 分钟。
#include <stdio.h>
#include <stdlib.h>#define ROW 10
#define COL 2// int g_grid[ROW][COL] = { {0, -1}, {2, 0}, {3, 0}, {4, 0}, {5, 0}, {6, 2}, {7, 3}, {8, 3}, {9, 4}, {10, 4}, {11, 5}, {1, 7} };
// int g_grid[ROW][COL] = { {0, -1}, {2, 0}, {3, 0}, {4, 0}, {5, 0}, {6, 2}, {7, 3}, {8, 3}, {9, 4}, {10, 4} };
int g_grid[ROW][COL] = { {0, -1}, {1, 0}, {2, 0}, {3, 0}, {4, 0}, {5, 1}, {6, 1}, {7, 2}, {8, 3}, {9, 5} };typedef struct n_tree {
int num; struct n_tree *child; struct n_tree *sibling; } n_tree;n_tree *g_root;
int g_group_cnt;n_tree* insert_node(n_tree *root, int child, int parent)
{ n_tree *tmp_child = NULL; n_tree *tmp_node = NULL;// parent == -1
// changed redudant ? if (parent == -1) { tmp_child = (n_tree *)malloc(sizeof(n_tree)); if (tmp_child == NULL) { return NULL; } memset(tmp_child, 0, sizeof(n_tree)); tmp_child->num = child; root = tmp_child; return root; }// self
if (root->num == parent) { // exist? tmp_child = (n_tree *)malloc(sizeof(n_tree)); if (tmp_child == NULL) { return NULL; } memset(tmp_child, 0, sizeof(n_tree)); tmp_child->num = child;if (root->child == NULL) {
root->child = tmp_child; } else { // add to child sibling tmp_node = root->child; while (tmp_node->sibling != NULL) { tmp_node = tmp_node->sibling;}
tmp_node->sibling = tmp_child; } return root; }// child ?
tmp_child = root->child; while (tmp_child != NULL) { insert_node(tmp_child, child, parent); tmp_child = tmp_child->sibling; }return root;
}int get_n_tree_result(n_tree *root)
{ int cnt = 0; n_tree *tmp_child = NULL;if (root->child == NULL) {
return 1; }// access child
tmp_child = root->child; while (tmp_child != NULL) { cnt += get_n_tree_result(tmp_child); printf("num is %d, cnt is %d\n", tmp_child->num, cnt); tmp_child = tmp_child->sibling; }printf("get %d\n", root->num);
// handle cnt++; if (cnt % 2 == 0) { g_group_cnt++; } return cnt; }void init_data()
{ g_group_cnt = 0; }int split_group(int grid[][COL], int grid_size)
{ int result; int i;init_data();
for (i = 0; i < grid_size; i++) { printf("insert %d %d\n", g_grid[i][0], grid[i][1]); g_root = insert_node(g_root, g_grid[i][0], grid[i][1]); } get_n_tree_result(g_root);// free mem
result = g_group_cnt; return result; }int main()
{ int ret; ret = split_group(g_grid, ROW); printf("ret is %d\n", ret); printf("Hello world!\n"); printf("haha, it's ok now\n"); return 0; }转载地址:http://diloi.baihongyu.com/