我假設它是無效的具有負座標。
public List<Location> adjacentLocations(Location location)
{
List<Location> locations = new ArrayList<Location>();
// Calculate all the adjacent positions relative to the specified point.
int row = location.getRow();
int col = location.getCol();
for (int r = row -1; r<row +2; r++)
{
for (int c = col -1; c < col + 2; c++)
{
if ((c > -1 && r > -1) && !(r == row && c == col))
{
locations.add(new Location(r, c));
}
}
}
return locations;
}
填妥類來說明用法:
package stacktest;
import java.util.ArrayList;
import java.util.List;
public class Location {
// Row and column positions.
private int row;
private int col;
public Location(int row, int col)
{
this.row = row;
this.col = col;
}
public int getRow()
{
return this.row;
}
public int getCol()
{
return this.col;
}
public String toString()
{
return "[" + row + ", " + col + "]";
}
public List<Location> adjacentLocations()
{
List<Location> locations = new ArrayList<Location>();
// Calculate all the adjacent positions relative to the specified point.
for (int r = row -1; r<row +2; r++)
{
for (int c = col -1; c < col + 2; c++)
{
if ((c > -1 && r > -1) && !(r == row && c == col))
{
locations.add(new Location(r, c));
}
}
}
return locations;
}
public static void main(String[] args)
{
ArrayList<Location> originalLocations = new ArrayList<Location>();
originalLocations.add(new Location(4, 10));
originalLocations.add(new Location(100, 100));
originalLocations.add(new Location(1, 0));
for (Location l: originalLocations)
{
List<Location> adjacent = l.adjacentLocations();
System.out.println("orig: " + l);
for (Location adj: adjacent)
{
System.out.println(" -> " + adj);
}
}
}
}
和輸出:
orig: [4, 10]
-> [3, 9]
-> [3, 10]
-> [3, 11]
-> [4, 9]
-> [4, 11]
-> [5, 9]
-> [5, 10]
-> [5, 11]
orig: [100, 100]
-> [99, 99]
-> [99, 100]
-> [99, 101]
-> [100, 99]
-> [100, 101]
-> [101, 99]
-> [101, 100]
-> [101, 101]
orig: [1, 0]
-> [0, 0]
-> [0, 1]
-> [1, 1]
-> [2, 0]
-> [2, 1]
提供幾個示例輸入以及您對每個樣本輸入的預期輸出。 –