问题描述:
在二维数组中
[
[1, 2, 3, 4, 5],
[16,17,18,19,6],
[15,24,25,20,7],
[14,23,22,21,8],
[13,12,11,10,9]
]
在此数据中输出的顺序为1,2,3,4,5……..25。写出的算法就是输出这样的数字。
编程思想:
1. 定义四个变量left、right、top、bottom四个分别记录左边最小值left、右边最大值right、顶部的最小值top、底部最大值bottom。
2. 输出一圈之后left、top都加1,right、bottom都减1。
3. 进行之后的内部圈的重复第一、二步骤,直到left>right && top>bottom
时候结束循环
代码如下:
package cn.wzq.sword_finger_offer;
public class LuoXuanHuiXingArray {
public int[][] array = {
{1, 2, 3, 4, 5},
{16, 17, 18, 19, 6},
{15, 24, 25, 20, 7},
{14, 23, 22, 21, 8},
{13, 12, 11, 10, 9}
};
public void display(int[][] array) {
int left = 0, right = array.length - 1, top = 0, bottom = array.length - 1;
while (left <= right && top <= bottom) {
// 1. 从Left到Right遍历
for (int x = left; x <= right; x++) {
println(array[top][x]);
}
top++;
// 2. 从Top到Bottom遍历
for (int y = top; y <= bottom; y++) {
println(array[y][right]);
}
right--;
// 3. 从Right到Left遍历
for (int x = right; x >= left; x--) {
println(array[bottom][x]);
}
bottom--;
// 4. 从Bottom到Top遍历
for (int y = bottom; y >= top; y--) {
println(array[y][left]);
}
left++;
}
}
public void println(Object object){
System.out.println(object);
}
public static void main(String[] arg){
LuoXuanHuiXingArray L = new LuoXuanHuiXingArray();
L.display(L.array);
}
}