2次元配列の任意の配列の位置から、相対的な位置 右, 下, 左, 上 にある値を取り出す。
forループでdColとdRowの値を順に取り出して、それを現在のインデックスの値に足すことで、右 下 左 上の順でその位置のインデックスを作成できる。
dCol[0]は1 dRow[0]は0なので 現在のインデックスが row = 1 col = 1 の時は nRow = 1 + 0 = 1, col = 1 + 1 = 2となり、右隣りの値が取り出せる。
サンプルコードはJavaを使用しています。
// 3x3配列で現在位置の4方向の値を取り出すサンプル public class NeighborTemplate4 { // 右, 下, 左, 上 の順番 final static int[] dCol = {1, 0, -1, 0}; final static int[] dRow = {0, 1, 0, -1}; final static String[] dirName = {"右", "下", "左", "上"}; public static void main(String[] args) { int[][] grid = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int h = grid.length; // 行数 int w = grid[0].length; // 列数 int row = 1, col = 1; // 中央 (値 = 5) System.out.println("現在地 ("+row+","+col+") = " + grid[row][col]); // 4方向を順に確認 for (int i = 0; i < 4; i++) { int nRow = row + dRow[i]; int nCol = col + dCol[i]; if (0 <= nRow && nRow < h && 0 <= nCol && nCol < w) { System.out.println(dirName[i] + " の値 = " + grid[nRow][nCol]); } } } } 出力 現在地 (1,1) = 5 右 の値 = 6 下 の値 = 8 左 の値 = 4 上 の値 = 2
右, 右下, 下, 左下, 左, 左上, 上, 右上 の値を取り出す場合。
// 3x3配列で現在位置の8方向の値を取り出すサンプル public class NeighborTemplate8 { // 右, 右下, 下, 左下, 左, 左上, 上, 右上 の順番 final static int[] dCol = {1, 1, 0, -1, -1, -1, 0, 1}; final static int[] dRow = {0, 1, 1, 1, 0, -1, -1, -1}; final static String[] dirName = { "右", "右下", "下", "左下", "左", "左上", "上", "右上" }; public static void main(String[] args) { int[][] grid = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int h = grid.length; // 行数 int w = grid[0].length; // 列数 int row = 1, col = 1; // 中央 (値 = 5) System.out.println("現在地 ("+row+","+col+") = " + grid[row][col]); // 8方向を順に確認 for (int i = 0; i < 8; i++) { int nRow = row + dRow[i]; int nCol = col + dCol[i]; if (0 <= nRow && nRow < h && 0 <= nCol && nCol < w) { System.out.println(dirName[i] + " の値 = " + grid[nRow][nCol]); } } } } ### 出力 ``` 現在地 (1,1) = 5 右 の値 = 6 右下 の値 = 9 下 の値 = 8 左下 の値 = 7 左 の値 = 4 左上 の値 = 1 上 の値 = 2 右上 の値 = 3 ```
関数にした場合。
import java.util.ArrayList; import java.util.List; public class NeighborFunction { // 右, 右下, 下, 左下, 左, 左上, 上, 右上 final static int[] dCol = {1, 1, 0, -1, -1, -1, 0, 1}; final static int[] dRow = {0, 1, 1, 1, 0, -1, -1, -1}; final static String[] dirName = { "右", "右下", "下", "左下", "左", "左上", "上", "右上" }; // 周囲の値を返す関数 public static ListgetNeighbors(int[][] grid, int row, int col) { int h = grid.length; // 行数 int w = grid[0].length; // 列数 List result = new ArrayList<>(); for (int i = 0; i < 8; i++) { int nRow = row + dRow[i]; int nCol = col + dCol[i]; if (0 <= nRow && nRow < h && 0 <= nCol && nCol < w) { result.add(dirName[i] + " の値 = " + grid[nRow][nCol]); } } return result; } public static void main(String[] args) { int[][] grid = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int row = 1, col = 1; // 中央 (値 = 5) System.out.println("現在地 ("+row+","+col+") = " + grid[row][col]); // 関数で取得して出力 List neighbors = getNeighbors(grid, row, col); for (String s : neighbors) { System.out.println(s); } } } ### 実行結果 ``` 現在地 (1,1) = 5 右 の値 = 6 右下 の値 = 9 下 の値 = 8 左下 の値 = 7 左 の値 = 4 左上 の値 = 1 上 の値 = 2 右上 の値 = 3 ```