Programming to find the area of a polygon

Topic :

Given a simple polygon (without gaps), its sides are either vertical or horizontal. Asked to calculate the area of ​​a polygon. The polygon is placed on an XY Cartesian plane with all its sides parallel to one of the two coordinate axes. 
Then give the coordinate values ​​of each vertex in a counterclockwise direction. All coordinate values ​​are integers (so the area of ​​the polygon is also an integer)
Input description : 
The first line gives the number of vertices n (n≤100) of the polygon. The next few lines each give the X and Y coordinates of a vertex of the polygon (both are integers separated by spaces). The vertices are given one by one in a counterclockwise direction. 
And the coordinate value of each vertex of the polygon is -200≤x,y≤200. The polygon is finally closed by drawing an edge from the last vertex to the first vertex.
Output description : 
An integer representing the area of ​​the polygon.
Example 
Example 1 
input 
10 
0 0 
4 0 
4 1 
3 1 
3 3 
2 3 
2 2 
1 2 
1 3 
0 3 

output 
9
Example 2 
input 
10 
0 0 
1 0 
1 5 
2 5 
2 2 
4 
2 4 
3 6 
3 6 6 
0 6 

output 
21

 code

public class duobianxing1 {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String str_0 = scan.nextLine().trim();
        int n = Integer.parseInt(str_0);
        ArrayList<ArrayList<Integer>> vector = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            String str_1 = scan.nextLine();
            String[] line_list_1 = str_1.trim().split(" ");
            ArrayList<Integer> temp_1 = new ArrayList<>();
            for (int j = 0; j < line_list_1.length; j++) {
                temp_1.add(Integer.parseInt(line_list_1[j]));
            }
            vector.add(temp_1);
        }
        scan.close();
        int result = solution(n, vector);
        System.out.println(result);
    }

    public static int solution(int n, ArrayList<ArrayList<Integer>> vector) {
        int result = 0,j;
        // TODO: 请在此编写代码 简写
        for(int i=0;i<n;i++){
            j=(i+1)%n;
            result += vector.get(i).get(0)*vector.get(j).get(1)-vector.get(j).get(0)*vector.get(i).get(1);
        }
        return Math.abs(result)/2;
    }
}

Area formula found

 Find a master to prove the formula (look at it vertically)

 

Guess you like

Origin blog.csdn.net/qq_40453972/article/details/126725518