问题描述:
样例如下:
代码如下:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class ProjectionArea {
public int projectionArea(int[][] grid) {
return topView(grid)+frontView(grid)+sideView(grid);
}
//俯视图
public int topView(int[][] grid){
int res=0;//扫描所有元素,若该点的元素值大于1,则表示在俯视图中存在一块小正方形
for (int i = 0; i <grid.length ; i++) {
for (int j = 0; j <grid[0].length ; j++) {
if (grid[i][j]>0)res++;
}
}
return res;
}
//正视图
public int frontView(int[][] grid){
int res=0;
for (int i = 0; i <grid[0].length ; i++) {
int temp=0;//记录该列最大值
for (int j = 0; j <grid.length ; j++) {
if (grid[j][i]>temp)temp=grid[j][i];
}
res+=temp;
}
return res;
}
//侧视图
public int sideView(int[][] grid){
int res=0;
for (int i = 0; i <grid.length ; i++) {
int temp=0;//记录该行的最大值
for (int j = 0; j <grid[0].length ; j++) {
if (grid[i][j]>temp){
temp=grid[i][j];
}
}
res+=temp;
}
return res;
}
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入二维数组行数");
int n=scanner.nextInt();
int[][] grid=new int[n][];
System.out.println("请输入二维数组(按行输入,元素之间用逗号隔开)");
try {
for (int i = 0; i <n ; i++) {
String[] temp=bufferedReader.readLine().split(",");
int[] a=new int[temp.length];
for (int j = 0; j <temp.length ; j++) {
a[j]=Integer.parseInt(temp[j]);
}
grid[i]=a;
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("该图的三视图之和为:");
ProjectionArea projectionArea=new ProjectionArea();
int res=projectionArea.projectionArea(grid);
System.out.println(res);
}
}
运行结果如下:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)