題目內容:
有一隊待列隊士兵,每個士兵有一個唯一編號,請完善以下 queues 函數,列出所有可能的列隊方式,不可重複。
請注意 queues 函數的健壯性
例:有士兵 5, 9, 14
可能的列隊方式如下
[5, 9, 14]
[5, 14, 9]
[9, 5, 14]
[9, 14, 5]
[14, 9, 5]
[14, 5, 9]
/**
* 深度優先遍歷
* 參數: soldiers 士兵編號數組
* count soldiers 中包含的士兵數量
* pFlag 記錄每個士兵是否被選過,選過置1,否則置0
* queueNo 排列序號
* depth 遞歸到第幾層
* temp_array 臨時存放排列數的數組
* return_array 士兵所有排列方式的遍歷結果數組
* 返回: void
**/
static void dfs(int* soldiers, int count, int* pFlag, int* queueNo, int depth, int *temp_array, int *return_array){
int i = 0;
int j = 0;
int x = 0;
if (depth == count)
{
for(x = 0; x<count; x++) return_array[*queueNo * count + x] = temp_array[x];
*queueNo += 1;
return;
}
for (i = 0; i < count; i++)
{
if (0 == pFlag[i])
{
j = i;
temp_array[depth] = soldiers[i];
pFlag[i] = 1;
dfs(soldiers, count, pFlag, queueNo, depth + 1, temp_array, return_array);
pFlag[j] = 0;
}
}
return;
}
/**
* 遍歷士兵的排列方式,並返回
* 參數: soldiers [int[]] 士兵編號數組
* count [int] soldiers 中包含的士兵數量
* queueCount [int*] 計算得到的不同的排列方式數量,輸出
* 返回: 士兵所有排列方式的遍歷結果數組,count 個爲一個排列方式,
* 共 queueCount 種不同排列,數組中應有 queueCount * count 個 int 數據,
* 返回內容的空間由 malloc 創建,外層代碼需要調用 free 釋放。
* 若失敗返回 NULL
**/
int* queues(int* soldiers, int count, int* queueCount)
{
// 補充本函數
int *return_array = NULL; //返回數組指針
int *pFlag =NULL; //狀態標誌位
int *temp_array = NULL;
int i;
int queueNo = 0; //隊列序號
//計算queueCount的值
*queueCount = 1;
for(i = 2;i<=count;i++) *queueCount *= i;
//申請空間
return_array = (int*)malloc(*queueCount * count * sizeof(int));
temp_array = (int*)malloc(count * sizeof(int));
pFlag = (int*)malloc(sizeof(int) * count);
memset(pFlag, 0x00, sizeof(int) * count);
//深度優先遍歷
dfs(soldiers, count, pFlag, &queueNo, 0, temp_array, return_array);
free(temp_array);
temp_array = NULL;
free(pFlag);
pFlag = NULL;
return return_array;
}
int main()
{
int soldiers[] = {5,9,14};
int* results;
int resultCount;
int i, j;
int soldierCount = sizeof(soldiers) / sizeof(int);
printf("待排列士兵:");
for (i = 0; i < soldierCount; i++)
printf(" %d", soldiers[i]);
printf("\n");
results = queues(soldiers, soldierCount, &resultCount);
if (results == NULL)
{
printf("遍歷排列方式失敗\n");
return -1;
}
printf("士兵可能隊列:\n");
for (i = 0; i < resultCount; i++)
{
printf(" [%d", results[i * soldierCount]);
for (j = 1; j < soldierCount; j++)
printf(", %d", results[i * soldierCount + j]);
printf("]\n");
}
free(results);
results = NULL;
return 0;
}