Open In App

Implement Simple 2D Segment Tree in Python

Last Updated : 01 Jun, 2024
Comments
Improve
Suggest changes
35 Likes
Like
Report

A 2D Segment Tree is a data structure that allows efficient querying and updating of two-dimensional arrays, such as matrices. It's an extension of the 1D segment tree, allowing range queries and updates in 2D. Here's a step-by-step implementation of a simple 2D Segment Tree in Python. We'll focus on building the segment tree, querying for the sum of a submatrix, and updating an element in the matrix.

Implementation of Simple 2D Segment Tree in Python

Step 1: Define the Segment Tree Node

First, let's define a class to represent each node of the 2D segment tree. Each node will store the sum of elements in its corresponding submatrix.

Step 2: Update Operation

Next, let's implement the update operation to modify the value of a specific element in the matrix.

Step 3: Range Sum Query

Now, let's implement the range sum query operation to calculate the sum of elements in a submatrix.

Step 4: Example Usage

Finally, let's provide an example of how to use the 2D segment tree for updating and querying.

2D Segment Tree in Python


Output
12
17



Article Tags :

Similar Reads