馬踏棋盤優化
阿新 • • 發佈:2018-12-20
之前做了個深搜遍歷求解的方法,未優化,一個下午沒有結果,而且程式碼尚不夠精簡
看了一下優化方法,又重做了一個,基本不需要時間就能得到一個解
一共一百來行,沾沾自喜一下
#include<stdio.h> #include<windows.h> #define MAX 8 #define NONE 0 #define START 1 #define INFINITE 88888 int chess[MAX][MAX]; int gowhere[][2] = { { 2, -1 }, { 2, 1 }, { -2, 1 }, { -2, -1 }, { 1, 2 }, { 1, -2 }, { -1, -2 }, { -1, 2 } };//用二維陣列更簡單 void initchess(); void traverchess(int i, int j, int num); bool judge(int i, int j); int judgeminpath(int i, int j); int main() { initchess(); int i, j; scanf_s("%d%d", &i, &j); traverchess(i, j, START); system("pause"); } void initchess() { int i, j; for (i = 0; i < MAX; i++) { for (j = 0; j < MAX; j++) { chess[i][j] = NONE; } } } void traverchess(int i, int j,int num) { if (num == MAX*MAX) { int x, y; chess[i][j] = MAX*MAX; for (x = 0; x < MAX; x++) { for (y = 0; y < MAX; y++) { printf("%4d ", chess[x][y]); } printf("\n"); } printf("\n"); return; } int recordc,count,min=INFINITE; for (count = 0; count < 8; count++)//for迴圈為貪心演算法核心,遍歷座標ij的周圍八個點,並由judgeminpath函式返回八個點的中每個點的可走路數 { if (!judge(i + gowhere[count][0], j + gowhere[count][1])) { continue; } int path = judgeminpath(i + gowhere[count][0], j + gowhere[count][1]); if (min > path) { min = path; recordc = count; } } if (min!=INFINITE) { chess[i][j] = num; traverchess(i + gowhere[recordc][0], j + gowhere[recordc][1], num + 1); chess[i][j] = NONE; } } bool judge(int i,int j) { if (i >= MAX || i < 0 || j >= MAX || j < 0) { return false; } if (chess[i][j] == NONE) { return true; } else { return false; } } int judgeminpath(int i, int j) { int c; int tag=0; for (c = 0; c < 8; c++) { if (judge(i + gowhere[c][0], j + gowhere[c][1])) { tag++; } } return tag; }