我喜欢@sprinter 的方式,因为它更简洁并且利用了 Java 8。
但这里有一个更详细的方法来解决这个枚举问题:
首先定义一个描述棋子运动的通用接口
interface Movement {
int x();
int y();
}
然后我们将使用一个枚举来实现其中一个片段的动作
enum BishopMovement implements Movement {
//the names for the enum constants
//indicate the direction of the movement and how far it goes
UpLeft1( -1, -1 ),
UpLeft2( -2, -2 ),
UpRight1( 1, -1 ),
UpRight2( 2, -2 ),
DownRight1( 1, 1 ),
DownRight2( 2, 2 ),
DownLeft1( -1, 1 ),
DownLeft2( -2, 2 );
final int x, y;
BishopMovement( int xOffset, int yOffset ){
x = xOffset;
y = yOffset;
}
@Override
public int x() {
return x;
}
@Override
public int y() {
return y;
}
}
这是骑士的另一个例子
enum KnightMovement implements Movement {
//again, the names say which movement they represent
UpLeft( -1, -2 ),
UpRight( 1, -2 ),
RightUp( 2, -1 ),
RightDown( 2, 1 ),
DownRight( 1, 2 ),
DownLeft( -1, 2 ),
LeftDown( -2, 1 ),
LeftUp( -2, -1 );
final int x, y;
KnightMovement( int xOffset, int yOffset ){
x = xOffset;
y = yOffset;
}
@Override
public int x() {
return x;
}
@Override
public int y() {
return y;
}
}
像这样定义每个部分有点乏味,但我确实喜欢将动作组织在一个枚举中。我想是个人喜好。
我也将在一个枚举中定义键盘中的键
enum Key {
//note that the order is important here
//because we'll be using ordinal() to easily
//convert between an int and a Key
Zero( 1, 3 ),
One( 0, 0 ),
Two( 1, 0 ),
Three( 2, 0 ),
Four( 0, 1 ),
Five( 1, 1 ),
Six( 2, 1 ),
Seven( 0, 2 ),
Eight( 1, 2 ),
Nine( 2, 2 ),
None( -1, -1 ); //default constant
final int x, y;
Key( int xOffset, int yOffset ){
x = xOffset;
y = yOffset;
}
//overriding toString because it'll be easier
//to record the moves
@Override
public String toString() {
String s = "";
if( !this.equals( None ) )
s += this.ordinal();
return s;
}
}
最后,解决方案
public class Solution {
static Key[][] keypad;
static final int x1 = 2, y1 = 3; //Key One will be at x=2, y=3
static {
keypad = new Key[7][10]; //extra padding
for( int x = 0; x < 7; x++ ){
for( int y = 0; y < 10; y++ ) {
keypad[x][y] = Key.None; //set all the elements to the default
}
}
for( Key k : Key.values() ) {
keypad[x1+k.x][y1+k.y] = k; //set all the keys
}
}
public static void main( String[] args ) {
int key = 1;
int totalMoves = 7;
String initialMovement = "-";
String allPossibleMoves = recursiveSolve( key, totalMoves, initialMovement, BishopMovement.values() );
//all the possible moves will be separated by spaces with a trailing space at the end
System.out.print( allPossibleMoves );
}
static String recursiveSolve( int key, int movesLeft, String moves, Movement[] possibleMoves ) {
String results="";
if( movesLeft > 0 ){
Key k = Key.values()[key], nextKey;
for( Movement m : possibleMoves ){
nextKey = keypad[x1+k.x+m.x()][y1+k.y+m.y()];
if( !nextKey.equals( Key.None ) ) {
results += recursiveSolve( nextKey.ordinal(), movesLeft - 1, moves + nextKey, possibleMoves );
}
}
}
else {
results = moves+" ";
}
return results;
}
}