Home > Java > Javagetting Started > body text

Use java to output a two-dimensional array clockwise

王林
Release: 2020-04-16 16:11:57
forward
3015 people have browsed it

Use java to output a two-dimensional array clockwise

Goal:

Output a two-dimensional array clockwise.

(Recommended tutorial: Getting started with java)

The code is implemented as follows:

public class 顺时针输出二维矩阵 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[][]arr={
				 {1,2,2,3},
				 {4,5,4,6},
				 {7,8,6,9},
				 {1,2,3,4}
				 };
		int k=0;
		for(int i = 0; i < arr.length;i++){
			for(int j = 0;j < arr[0].length;j++){
				k++;
				System.out.print(arr[i][j]+" ");
				if(k % 4 == 0){
					System.out.println("");
				}
			}	
		}
		System.out.println("");
		System.out.println(arr[0].length);//列数
		
		System.out.println(arr.length);//行数	
		print(arr);
	}
	static void print (int[][]arr){
		int leftUpRow = 0;//最左行
		int leftUpCol = 0;//最左列
		int rightDownRow = arr.length-1;//最右列
		int rightDownCol = arr[0].length-1;//最右列
		while(leftUpRow <= rightDownRow && leftUpCol  <= rightDownCol){
			int row = leftUpRow, col = leftUpCol;
			//矩阵的第一行,此时行不变,列++
			while(col <= rightDownCol){
				System.out.print(arr[row][col++]+" ");
			}
			//矩阵右边第一列  此时行++,列不变
			//将 col,row 恢复
			col = rightDownCol;
			row++;
			while(row <= rightDownRow){
				System.out.print(arr[row++][col]+" ");
			}
			//矩阵的最下面一行  此时 行不变 列--
			//还需要恢复 col row 的值
			row = rightDownRow;
			col--;
			while(col >= leftUpCol){
				System.out.print(arr[row][col--]+" ");
			}
			//矩阵最左边一列,此时行--,列不变
			//继续恢复 col row的值
			col = leftUpCol;
			row--;
			while(row > leftUpRow){
				System.out.print(arr[row--][col]+" ");
			}
			leftUpRow++;
			leftUpCol++;
			rightDownRow--;
			rightDownCol--;
		
		}
	}
}
Copy after login

Output results:

1 2 2 3 
4 5 4 6 
7 8 6 9 
1 2 3 4 

1 2 2 3 6 9 4 3 2 1 7 4 5 4 6 8
Copy after login

Recommended related video tutorials :java视频

The above is the detailed content of Use java to output a two-dimensional array clockwise. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!