最近比较忙,比较忙,比较忙不过大概步骤就是。。具体代码你就自己琢磨吧,不能懒啊。。 private int currentMinSteps = Integer.MAX_INT; // this is the recursion I mentioned void find (Tile currentTile, int currentSteps) { Tile tiles[] = findTilesAround(currentTile); sortTilesByItsNumber(tiles); for (Tile tile: tiles) { if (hasVisited(tile)) continue; if (calculateCurrentTotal(tile) == halfTotal){ if (isSolutionCuttable()) // the step I mentioned to test if the solution can be cut by just once currentMinSteps = currentMinSteps < currentSteps ? currentMinSteps : currentSteps; continue; } else if (currentSteps >= currentMinSteps) continue; // this is where time gets saved else find (tile, currentSteps + 1); // the recursive step, which will find all solutions } }
然后new一个栈遍历整个M * N的数据 ,再定义一个变量statckCount,每次push一个数据进来就加上去。如果stackCount == maxCount/2,就可以得到解了。
每一步都从数字最大的格子找起(递归)
当找到一条路时,再判断这条路是否能剪切。如果能,则记下格子的数量为目前最优解
当搜索其他路径时,如果格子数量超过最优解,则终止该路径而转向其他路径判断解是否可剪切,选一个路径之外的格子,做一次遍历,遍历到的格子总数与当前路径格子数相加,看是否为m*n选路径外的格子,我就不说了有很多种方法。。
private int currentMinSteps = Integer.MAX_INT;
// this is the recursion I mentioned
void find (Tile currentTile, int currentSteps) {
Tile tiles[] = findTilesAround(currentTile);
sortTilesByItsNumber(tiles);
for (Tile tile: tiles) {
if (hasVisited(tile)) continue;
if (calculateCurrentTotal(tile) == halfTotal){
if (isSolutionCuttable()) // the step I mentioned to test if the solution can be cut by just once
currentMinSteps = currentMinSteps < currentSteps ? currentMinSteps : currentSteps;
continue;
}
else if (currentSteps >= currentMinSteps) continue; // this is where time gets saved
else
find (tile, currentSteps + 1); // the recursive step, which will find all solutions
}
}
贪心+回溯 实现。
http://blog.csdn.net/jopus/article/details/19082697