代码
public static void solve(String[][] datas, int rows, int cols, int offset) { boolean isReturn = isEnd(rows, cols, offset); if (isReturn) { return; } int row_index = offset; int col_index = offset; int row_max = rows - 1 - offset; int col_max = cols - 1 - offset; while (col_index <= col_max) { System.out.print(datas[row_index][col_index]); if (col_index != col_max) { col_index++; } else { break; } } while (row_index < row_max) { row_index++; System.out.print(datas[row_index][col_index]); } while (col_index > offset) { col_index--; System.out.print(datas[row_index][col_index]); } while (row_index > (offset + 1)) { row_index--; System.out.print(datas[row_index][col_index]); } System.out.println(""); solve(datas, rows, cols, offset + 1); } private static boolean isEnd(int rows, int cols, int offset) { int minSize = rows > cols ? cols : rows; if (minSize % 2 == 0) { return offset == minSize / 2; } return (minSize / 2 + 1) == offset; }
main 方法
public static void main(String[] args) { String[][] datas1 = { { "a", "b", "c", "d", "e" }, { "f", "g", "h", "i", "j" }, { "k", "l", "m", "n", "o" }, { "p", "q", "r", "s", "t" }, }; String[][] datas2 = { { "a", "b", "c" }, { "f", "g", "h" }, { "k", "l", "m" }, { "p", "q", "r" }, }; String[][] datas3 = { { "a", "b", "c", "d", "e" }, { "f", "g", "h", "i", "j" }, { "k", "l", "m", "n", "o" }, { "p", "q", "r", "s", "t" }, { "u", "v", "w", "x", "y" } }; solve(datas1, 4, 5, 0); System.out.println("------------------"); solve(datas2, 4, 3, 0); System.out.println("------------------"); solve(datas3, 5, 5, 0); }
输出