我被公式打败了,这是使用地图的蛮力。
public class MapPointToIndex {
private Map<Point, Integer> map;
private int index, rowcount;
public MapPointToIndex(int rows, int columns) {
map = new HashMap<Point, Integer>();
for (int i = rows - 1; i >= 0; i--) {
index += rowcount;
for (int j = 0; j < columns; j++) {
Point p = new Point(j, i);
map.put(p, index);
index++;
}
rowcount = 1;
}
}
public int getIndex(Point point){
return map.get(point);
}
public static void main(String[] args) {
MapPointToIndex one = new MapPointToIndex(3, 3);
System.out.println(one.map);
}
}
出去:
{java.awt.Point[x=0,y=0]=8, java.awt.Point[x=2,y=2]=2, java.awt.Point[x=1,y=2]=1, java.awt.Point[x=2,y=1]=6, java.awt.Point[x=1,y=1]=5, java.awt.Point[x=2,y=0]=10, java.awt.Point[x=0,y=2]=0, java.awt.Point[x=1,y=0]=9, java.awt.Point[x=0,y=1]=4}