问题描述: 样例如下: 代码如下:
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;
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);
}
}
运行结果如下:
|