这道题是面试某公司时遇到的一道题,当然思维有些混乱,没有解出来。
经过分析此题要点是边界处理,即向右上移动时,超出九宫格时的处理过程,右上冲突时向下移动不需要考虑边界问题,均未超出边界。
当时面试官的要求是不论语言,30 分钟输出九宫格,不需要边框样式。
public static void main(String[] args) {
int count = 1;
int x = 0;
int y = 1;
int[][] arr = new int[3][3];
arr[0][1] = 1;
while (count < 9) {
int[] index = getIndex(arr, x, y);
x = index[0];
y = index[1];
arr[x][y] = ++count;
}
System.out.println(Arrays.toString(arr[0]));
System.out.println(Arrays.toString(arr[1]));
System.out.println(Arrays.toString(arr[2]));
}
public static int[] getIndex(int[][] arr, int x, int y) {
int tempX = x - 1 < 0 ? 2 : x - 1;
int tempY = y + 1 > 2 ? 0 : y + 1;
if (arr[tempX][tempY] != 0) {
return new int[]{x + 1, y};
} else {
return new int[]{tempX, tempY};
}
}