【數組】之宇宙無敵360度反覆橫跳之旋轉打印數組

在這裏插入圖片描述
算法上沒有難度,需要注意邏輯問題設計。
思路:

  • 最容易理解的方法是層層剝開,一圈一圈打印
  • 左上角來兩個指針橫縱座標,右下角也是
  • 寫一個方法用來打印圈
  • 當左上角和右下角撞見了,停止

打印圈:

			int curR = r1;//左上角橫座標
			int curC = c1;//左上角縱座標
			while (curC != c2) {//從左到右
				System.out.print(matrix[curR][curC] + " ");
				curC++;
			}//到頭了
			while (curR != r2) {//從上到下
				System.out.print(matrix[curR][curC] + " ");
				curR++;
			}//到了
			while (curC != c1) {//從右到左
				System.out.print(matrix[curR][curC] + " ");
				curC--;
			}
			while (curR != r1) {//從下到上
				System.out.print(matrix[curR][curC] + " ");
				curR--;
			}

需要考慮如果只有一行或者一列的情況

		if (r1 == r2) {
			for (int i = c1; i <= c2; i++) {
				System.out.print(matrix[r1][i] + " ");
			}
		} else if (c1 == c2) {
			for (int i = r1; i <= r2; i++) {
				System.out.print(matrix[i][c1] + " ");
			}
		}

完整代碼:


/*
 * 旋轉打印數組*/
public class Main {
	public static void main(String[] args) throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		String[] numStrings = in.readLine().split(" ");
		int n = Integer.valueOf(numStrings[0]);
		int m = Integer.valueOf(numStrings[1]);
		int[][] matrix = new int[n][m];
		for (int i = 0; i < n; i++) {
			String[] lineStrings = in.readLine().split(" ");
			for (int j = 0; j < m; j++) {
				matrix[i][j] = Integer.valueOf(lineStrings[j]);
			}
		}
		spiralOrderPrint(matrix);

	}

	public static void spiralOrderPrint(int[][] matrix) {
	
        if (matrix==null||matrix.length==0||matrix[0]==null||matrix[0].length==0) {
			return;
		}
		int r1 = 0, c1 = 0;
		int r2 = matrix.length - 1, c2 = matrix[0].length - 1;
		while (r1 <= r2 && c1 <= c2) {
			printEdge(matrix, r1++, c1++, r2--, c2--);
		}

	}

	private static void printEdge(int[][] matrix, int r1, int c1, int r2, int c2) {
		if (r1 == r2) {
			for (int i = c1; i <= c2; i++) {
				System.out.print(matrix[r1][i] + " ");
			}
		} else if (c1 == c2) {
			for (int i = r1; i <= r2; i++) {
				System.out.print(matrix[i][c1] + " ");
			}
		} else {
			int curR = r1;
			int curC = c1;
			while (curC != c2) {
				System.out.print(matrix[curR][curC] + " ");
				curC++;
			}
			while (curR != r2) {
				System.out.print(matrix[curR][curC] + " ");
				curR++;
			}
			while (curC != c1) {
				System.out.print(matrix[curR][curC] + " ");
				curC--;
			}
			while (curR != r1) {
				System.out.print(matrix[curR][curC] + " ");
				curR--;
			}

		}
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章