您好,登錄后才能下訂單哦!
經典的遞歸程序設計中的2到題目
1、八皇后問題
國際象棋棋盤走法,用遞歸實現所有的可能性;
棋盤:
(1)、代碼如下:
#include<stdio.h> typedef unsigned char boolean; #define TRUE 1 #define FALSE 0 #define EIGHT 8 void showChess(int (*chess)[EIGHT]); //顯示棋盤 boolean isSafe(int (*chess)[EIGHT], int row, int col); //判斷這個位置是否安全 void eightQueen(int (*chess)[EIGHT], int row); //八皇后的遞歸程序 void eightQueen(int (*chess)[EIGHT], int row){ int colIndex; if(row >= EIGHT){ showChess(chess); }else{ for(colIndex = 0; colIndex < EIGHT; colIndex++){ if(isSafe(chess, row, colIndex) == TRUE){ chess[row][colIndex] = 1; eightQueen(chess, row+1); chess[row][colIndex] = 0; } } } } boolean isSafe(int (*chess)[EIGHT], int row, int col){ int rowIndex; int colIndex; for(rowIndex = row-1; rowIndex >= 0; rowIndex--){ if(chess[rowIndex][col] == 1){ return FALSE; } } for(rowIndex = row-1, colIndex = col-1; rowIndex >= 0 && colIndex >= 0; rowIndex--, colIndex--){ if(chess[rowIndex][colIndex] == 1){ return FALSE; } } for(rowIndex = row-1, colIndex = col+1; rowIndex >= 0 && colIndex < EIGHT; rowIndex--, colIndex++){ if(chess[rowIndex][colIndex] == 1){ return FALSE; } } return TRUE; } void showChess(int (*chess)[EIGHT]){ int i; int j; int static count; printf("解:%d\n", ++count); for(i = 0; i < EIGHT; i++){ for(j = 0; j < EIGHT; j++){ printf("%4d ", chess[i][j]); } printf("\n"); } } void main(void){ int chess[EIGHT][EIGHT] = {0}; eightQueen(chess, 0); }
(2)、運行結果:
因為4個方向,每一個方向都有23種解法!!!
2、全排列問題
從n個數據中挑選m個數據,每個數據只能取一次,輸出其全部組合的可能性;
(1)、代碼如下:
#include<stdio.h> #include<string.h> void fullArray(char *sourceStr, int sourceLen, int *used, int i, char *resStr, int count); void fullArray(char *sourceStr, int sourceLen, int *used, int i, char *resStr, int count){ int index; if(i >= count){ printf("%s\n", resStr); }else{ for(index = 0; index < sourceLen; index++){ if(used[index] == 0){ resStr[i] = sourceStr[index]; used[index] = 1; fullArray(sourceStr, sourceLen, used, i+1, resStr, count); used[index] = 0; } } } } void main(void){ char sourceStr[80]; int used[80] = {0}; char resStr[80] = {0}; int count; printf("請輸入字符串: "); gets(sourceStr); printf("請問要幾個進行全排列? "); scanf("%d", &count); fullArray(sourceStr, strlen(sourceStr), used, 0, resStr, count); }
(2)、運行結果:
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。