Open In App

Matrix Index Validation and Update

Last Updated : 04 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an integer two-dimensional array (matrix), and a query for an index in the matrix with a value, the task is to check whether the index in the query is valid or out of bound. If the index is valid, update the value at that index with the value provided in the query.

Examples:

Input: matrix[3][4] = {{1, 0, 0, 0}, {0, 0, 5, 0}, {0 ,0 ,0 ,0}}, matrix[4][2] = 42
Output: Error: Row index out of range
Explanation: we are accessing the index in the matrix which is out of range.

Input: matrix[3][4] = {{1, 0, 0, 0}, {0, 0, 5, 0}, {0, 0, 0, 0}} matrix[1][2]=100
Output: {{1, 0, 0, 0}, {0, 0, 100,0}, {0, 0, 0, 0}}
Explanation: we are accessing the index in the matrix in the range and updating, so we are printing the matrix

Approach: To solve the problem follow the below idea:

  • Cell (r,c) is in the matrix if the number of rows is greater than r and the number of columns is greater than c.
  • If the cell is out of range of the matrix, it is impossible to update the cell in the matrix.
  • If the cell is present in the matrix then update the cell and print the the matrix.

Implementation of the above approach:

C++




// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
 
void update(vector<vector<int>> &matrix, int r, int c, int value)
{
    // Check if given cell (r, c) exists
    // in matrix or not
    if (matrix.size() <= r || matrix[0].size() <= c) {
        cout << "Trying to update cell which is "
                "out of range in the matrix\n";
        return;
    }
 
    // As cell (i,j) is present in the matrix,
    // update the cell with val
    else {
        matrix[r] = value;
 
        // Printing the matrix after the update
        for (int i = 0; i < matrix.size(); i++) {
            for (int j = 0; j < matrix[0].size(); j++) {
                cout << matrix[i][j] << " ";
            }
            cout << "\n";
        }
    }
}
 
// Drivers code
int main()
{
    // Create a matrix of integers with
    // 3 rows and 4 columns
    vector<vector<int>> matrix = { { 1, 0, 0, 0 },
                                    { 0, 0, 5, 0 },
                                    { 0, 0, 0, 0 } };
 
    // Integer i and j represent the cell
    // which should be updated with a value val;
    int i = 2; // Note: Changed i from 3 to 2
    int j = 1; // Note: Changed j from 2 to 1
    int val = 100;
 
    // Update the given cell (i, j) with a value val
    update(matrix, i, j, val);
 
    return 0;
}


Java




import java.util.ArrayList;
 
public class Main {
    public static void
    update(ArrayList<ArrayList<Integer> > matrix, int r,
           int c, int value)
    {
        // Check if given cell (r, c) exists in the matrix
        // or not
        if (matrix.size() <= r
            || matrix.get(0).size() <= c) {
            System.out.println(
                "Trying to update cell which is out of range in the matrix");
            return;
        }
        else {
            matrix.get(r).set(c, value);
 
            // Printing the matrix after the update
            for (int i = 0; i < matrix.size(); i++) {
                for (int j = 0; j < matrix.get(0).size();
                     j++) {
                    System.out.print(matrix.get(i).get(j)
                                     + " ");
                }
                System.out.println();
            }
        }
    }
 
    public static void main(String[] args)
    {
        // Create a matrix of integers with 3 rows and 4
        // columns
        ArrayList<ArrayList<Integer> > matrix
            = new ArrayList<>();
        matrix.add(new ArrayList<Integer>() {
            {
                add(1);
                add(0);
                add(0);
                add(0);
            }
        });
        matrix.add(new ArrayList<Integer>() {
            {
                add(0);
                add(0);
                add(5);
                add(0);
            }
        });
        matrix.add(new ArrayList<Integer>() {
            {
                add(0);
                add(0);
                add(0);
                add(0);
            }
        });
 
        // Cell (i, j) to be updated with value
        int i = 3;
        int j = 2;
        int val = 100;
 
        // Update the given cell (i, j) with the value val
        update(matrix, i, j, val);
    }
}


Python3




# Python Implementation
def update(matrix, r, c, value):
    # Check if given cell (r, c) exist in matrix or not
    if len(matrix) <= r or len(matrix[0]) <= c:
        print("Trying to update cell which is out of range in the matrix")
        return
 
    # As cell (i,j) is present in the matrix, update the cell with value
    else:
        matrix[r] = value
 
        # Printing the matrix after the updation
        for i in range(len(matrix)):
            for j in range(len(matrix[0])):
                print(matrix[i][j], end=" ")
            print()
 
# Drivers code
if __name__ == "__main__":
    # Create a matrix of integers with 3 rows and 4 columns
    matrix = [[1, 0, 0, 0],
              [0, 0, 5, 0],
              [0, 0, 0, 0]]
 
    # integer i and j represents the cell which should be updated with a value val
    i = 3
    j = 2
    val = 100
 
    # Update the given cell(i,j) with a value val
    update(matrix, i, j, val)
     
# This code is contributed by Sakshi


C#




// C# code for the above approach:
using System;
using System.Collections.Generic;
 
public class GFG
{
    static void Update(List<List<int>> matrix, int r, int c, int value)
    {
        // Check if given cell (r, c) exists in matrix or not
        if (matrix.Count <= r || matrix[0].Count <= c)
        {
            Console.WriteLine("Trying to update cell which is out of range in the matrix");
            return;
        }
        else
        {
            // As cell (r, c) is present in the matrix,
              // update the cell with value
            matrix[r] = value;
 
            // Printing the matrix after the update
            for (int i = 0; i < matrix.Count; i++)
            {
                for (int j = 0; j < matrix[0].Count; j++)
                {
                    Console.Write(matrix[i][j] + " ");
                }
                Console.WriteLine();
            }
        }
    }
 
    static void Main()
    {
        // Create a matrix of integers with 3 rows and 4 columns
        List<List<int>> matrix = new List<List<int>>
        {
            new List<int> { 1, 0, 0, 0 },
            new List<int> { 0, 0, 5, 0 },
            new List<int> { 0, 0, 0, 0 }
        };
 
        // Integer i and j represent the cell which
         // should be updated with a value val
        int i = 3;
        int j = 2;
        int val = 100;
 
        // Update the given cell (i, j) with a value val
        Update(matrix, i, j, val);
    }
}


Javascript




function update(matrix, r, c, value) {
    // Check if the given cell (r, c) exists in the matrix or not
    if (matrix.length <= r || matrix[0].length <= c) {
        console.log("Trying to update cell which is out of range in the matrix");
        return;
    } else {
        // Update the cell with the given value
        matrix[r] = value;
 
        // Printing the matrix after the update
        for (let i = 0; i < matrix.length; i++) {
            for (let j = 0; j < matrix[0].length; j++) {
                console.log(matrix[i][j] + " ");
            }
            console.log("\n");
        }
    }
}
 
// Driver code
function main() {
    // Create a matrix of integers with 3 rows and 4 columns
    let matrix = [
        [1, 0, 0, 0],
        [0, 0, 5, 0],
        [0, 0, 0, 0]
    ];
 
    // Cell (i, j) to be updated with a value val
    let i = 2; // Note: Changed i from 3 to 2
    let j = 1; // Note: Changed j from 2 to 1
    let val = 100;
 
    // Update the given cell (i, j) with a value val
    update(matrix, i, j, val);
}
 
// Call the main function to execute the code
main();


Output

Trying to update cell which is out of range in the matrix









Time Complexity: O(n*m), where n and m are rows and columns.
Auxillary space: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads