Find 3 in a two-dimensional array

Source: Internet
Author: User

Determines whether the array is empty, returns false for NULL

??

Do not enter the loop empty

??

Number of rows obtained for the matrix:rows=matrix.length

Number of columns to get matrix:columns=matrix[0].length

??

Starting from the top right corner, initialize row and column:row=0,column=columns-1;

??

So The while condition is row<rows&&column>=0

??

If found, that is matrix[row][column]=number, and found is set to true

??

If not found, the current number is greater than numbers, find on the left,column--

??

The current number is less than numbers, find on the right,row++

??

Package Findinmatrix;

??

public class Findinmatrix {

??

public static void Main (string[] args) {

TODO auto-generated Method Stub

Test1 ();

Test2 ();

}

??

static void Test1 () {

int matrix[][] = {{1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13},

{6, 8, 11, 15}};

System.out.println (Find (Matrix, 1));

}

??

static void Test2 () {

SYSTEM.OUT.PRINTLN (Find (NULL, 7));

}

??

Static Boolean find (int[][] matrix, int number) {

??

Boolean found = false;

??

if (Matrix! = null) {

??

int rows = Matrix.length;

int columns = Matrix[0].length;

int row = 0;

int column = Columns-1;

??

while (Row < rows && column >= 0) {

if (matrix[row][column] = = number) {

Found = true;

Break

} else if (Matrix[row][column] > number) {

--column;

} else {

++row;

}

}

}

return found;

}

}

Find 3 in a two-dimensional array

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.