这似乎比你做的更复杂......所以不太确定它是否有帮助。我只是针对给定的示例对其进行了测试,但如果我没有完全误解这个问题,你可以只使用几个循环,所以动态编程没有明显的用途。
static boolean h(int[] luckySpot,int[][] parkingLot){
// check if parking spot given contains a 1
// (check if it's a valid parking spot)
for(int i=luckySpot[0];i<=luckySpot[2];i++){
for(int j=luckySpot[1];j<=luckySpot[3];j++){
if(parkingLot[i][j]==1) return false;
}
}
// check if the car parked vertically
if( Math.abs(luckySpot[0]-luckySpot[2]) >
Math.abs(luckySpot[1]-luckySpot[3])) {
// check for empty path going to the top
outerloop:
for(int i=0;i<luckySpot[0];i++){
for(int j=luckySpot[1];j<=luckySpot[3];j++){
if(parkingLot[i][j]==1) break outerloop;
}
if(i==luckySpot[0]-1) return true;
}
// check for empty path going to the bottom
for(int i=luckySpot[2]+1;i<parkingLot.length;i++){
for(int j=luckySpot[1];j<=luckySpot[3];j++){
if(parkingLot[i][j]==1) return false;
}
if(i==parkingLot.length-1) return true;
}
}
// the car parked horizontally
else{
// check for empty path going to the left
outerloop:
for(int i=luckySpot[0];i<=luckySpot[2];i++){
for(int j=0;j<luckySpot[1];j++){
if(parkingLot[i][j]==1) break outerloop;
}
if(i==luckySpot[2]) return true;
}
// check for empty path going to the right
for(int i=luckySpot[0];i<=luckySpot[2];i++){
for(int j=luckySpot[3]+1;j<parkingLot[0].length;j++){
if(parkingLot[i][j]==1) return false;
}
if(i==luckySpot[2]) return true;
}
}
return false;
}
public static void main(String[] args) {
/*
"for safety reasons, the car can only move in two directions inside
the parking lot -- forwards or backwards along the long side of the car"
i assume this to mean that the direction the car travels is parallel
to the long side of the car
*/
int[] carDimensions = {3, 2};
int [][] parkingLot = {
{1, 0, 1, 0, 1, 0},
{1, 0, 0, 0, 1, 0},
{1, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 1, 1}
};
int[] luckySpot={1, 1, 2, 3};
System.out.println(h(luckySpot,parkingLot));
}