算法|趣味算法-青蛙过河

趣味编程-青蛙过河:



两队青蛙,河左边3只,右边3只,青蛙过河要踩着石头,每次移动青蛙最多可以跳过对面的一只青蛙,但必须落在空的石头上。





算法原则:
每次只移动一只青蛙。
1)检查整个路径左侧青蛙越过右侧青蛙跳到空白石头上的情况;
2)检查整个路径右左侧青蛙越过左侧青蛙跳到空白石头上的情况;

3)检查整个路径左侧青蛙可以直接向右移动到空白石头上的情况,并且保证移动后向左的青蛙会与向右的青蛙相邻;

4)检查整个路径右侧青蛙直接向左移动到空白石头上的情况,并且保证移动后向右的青蛙会与向左的青蛙相邻;



到达对岸时结果 +1;
【算法|趣味算法-青蛙过河】

#include void print_road(int arrRoad[], int nLen) { int i = 0; for (i = 0; i < nLen; i++) { if (arrRoad[i] < 0) printf("-> "); else if (arrRoad[i] > 0) printf("<- "); else printf("O "); } printf("\n\n"); }void swap(int *nN1, int *nN2) { int nTmp = 0; nTmp = *nN1; *nN1 = *nN2; *nN2 = nTmp; }// left side the number is less than 0 // right side the number is bigger than 0 // empty grid is 0 int move_frog(int arrRoad[], int nLen, int nEmptyGrid) { int i = 0; intbMove = 1; int nSuccessCount = 0; // move the left side while(nSuccessCount < nLen - 1) { bMove = 1; for (i = 0 ; i < nEmptyGrid && bMove; i++) { if ((arrRoad[nEmptyGrid-2] < 0) && (arrRoad[nEmptyGrid-1] > 0)) { swap(&arrRoad[nEmptyGrid-2], &arrRoad[nEmptyGrid]); if (nEmptyGrid == nLen - 1) nSuccessCount++; nEmptyGrid -= 2; print_road(arrRoad, nLen); bMove = 0; break; } }for (i = nLen-1; i > nEmptyGrid && bMove; i--) { if ((arrRoad[nEmptyGrid+2] > 0) && (arrRoad[nEmptyGrid+1] < 0)) { swap(&arrRoad[nEmptyGrid+2], &arrRoad[nEmptyGrid]); if (nEmptyGrid == 0) nSuccessCount++; print_road(arrRoad, nLen); nEmptyGrid += 2; bMove = 0; break; } }for (i = 0; i < nEmptyGrid && bMove; i++) { if ((arrRoad[nEmptyGrid - 1] < 0) && (nEmptyGrid < nLen - 2 && (arrRoad[nEmptyGrid - 2]) != arrRoad[nEmptyGrid+1])) { swap(&arrRoad[nEmptyGrid-1], &arrRoad[nEmptyGrid]); if (nEmptyGrid == nLen - 1) nSuccessCount++; print_road(arrRoad, nLen); nEmptyGrid -= 1; bMove = 0; break; } }for (i = nLen-1; i > nEmptyGrid && bMove; i--) { if ((arrRoad[nEmptyGrid+1] > 0) && (nEmptyGrid > 0 && arrRoad[nEmptyGrid+2] != arrRoad[nEmptyGrid-1])) { swap(&arrRoad[nEmptyGrid+1], &arrRoad[nEmptyGrid]); if (nEmptyGrid == 0) nSuccessCount++; print_road(arrRoad, nLen); nEmptyGrid += 1; bMove = 0; break; } } } }int main() { int arrTest[7] = {-1,-1,-1,0,1,1,1}; int n = 0; print_road(arrTest, 7); move_frog(arrTest, 7, 3); scanf("%d", &n); return 0; }




算法复杂度:
青蛙个数: N
O(N) = N * (N/2)






    推荐阅读