Simple Matrix Practice Using PHP

Lesson Overview

Welcome to today's lesson covering Simple Matrix Practice. This is where we traverse the arena of two-dimensional data structures, commonly known as matrices. Matrices play an instrumental role in many domains of programming, such as machine learning, computer vision, and game development, making it important for you to understand how to effectively manipulate and traverse them.

Quick Example

To explore PHP matrices, it's essential to understand that a matrix is simply a two-dimensional array, with each row being an array. Given this structure, we can easily access matrix elements using the indices of the row and the column. Our practice problems will be based on similar logic, where we traverse and manipulate matrix data.

One practical exercise that we will cover is, given a sorted matrix where each row and column is sorted in ascending order, having to search for a particular target value. This exercise enhances your problem-solving skills and deepens your understanding of matrix traversal.

Since the matrix is sorted both row-wise and column-wise, we can leverage this property for an efficient search. Start from the top-right corner of the matrix:

  • If the current element equals the target, you've found the value.
  • If the current element is greater than the target, move left (one column back).
  • If the current element is less than the target, move down (one row forward).

Continue these steps until you either find the target or exhaust the search space. This method ensures that each step efficiently narrows down the potential search area.

Here is a PHP implementation of this logic:

<?php

class Solution {

    public static function searchMatrix($matrix, $target) {
        $rows = count($matrix);
        $cols = count($matrix[0]);

        // Start from the top-right corner
        $row = 0;
        $col = $cols - 1;

        while ($row < $rows && $col >= 0) {
            if ($matrix[$row][$col] == $target) {
                return true;
            } else if ($matrix[$row][$col] > $target) {
                $col--; // Move left
            } else {
                $row++; // Move down
            }
        }

        return false; // Target not found
    }

    public static function main() {
        $matrix = [
            [1, 4, 7, 11, 15],
            [2, 5, 8, 12, 19],
            [3, 6, 9, 16, 22],
            [10, 13, 14, 17, 24],
            [18, 21, 23, 26, 30]
        ];

        $target = 5;
        $found = self::searchMatrix($matrix, $target);

        if ($found) {
            echo "Target found\n";
        } else {
            echo "Target not found\n";
        }
    }
}

?>
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal