Maison  >  Article  >  Java  >  Utilisez Java pour générer un tableau bidimensionnel dans le sens des aiguilles d'une montre

Utilisez Java pour générer un tableau bidimensionnel dans le sens des aiguilles d'une montre

王林
王林avant
2020-04-16 16:11:572942parcourir

Utilisez Java pour générer un tableau bidimensionnel dans le sens des aiguilles d'une montre

Objectif :

Produire un tableau bidimensionnel dans le sens des aiguilles d'une montre.

(Tutoriel recommandé : Premiers pas avec Java)

Le code est implémenté comme suit :

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--;
		
		}
	}
}

Résultat de sortie :

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

Tutoriels vidéo associés recommandés :vidéo Java

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer