Finding in a two-dimensional array

Source: Internet
Author: User

Description: Give you a two-dimensional matrix, each row from left to right increment, each column from the top down, give you a Val, let you determine whether Val in the matrix appears.

Thinking: Judging from the bottom left, or the upper right corner. As in the lower left corner, if the lower left corner is smaller than Val, then the column does not satisfy the condition (because it is incremented from the top), if the lower-left corner is larger than Val, the line does not meet the criteria (because it increments from left to right).

#include <iostream> #include <bits/stdc++.h>using namespace Std;class matrix{Public:matrix () {}/            /Matrix (int _r,int _c): R (_r), C (_r) {} void input () {cin>>r >> C;                for (int i = 0, i < R; i++) {for (int j = 0; J < C; j + +) {cin>>mat[i][j];        }} cin>>val;            } bool exist () {int cc = C;            c = 0;            r--;                while (r >= 0 && C < cc) {if (mat[r][c] = = val) return true;                else if (Mat[r][c] < val) {C + +;                }else if (Mat[r][c] > val) {r--;        }} return false;        } ~matrix () {} private:int R, C, Val; int mat[50][50];};    int main () {Matrix tes;    Tes.input ();    if (Tes.exist ()) {cout<< "exist" <<endl; }else{cout<< "not exist" <<endl; } return 0;} /*4 41 2 8 92 4 9 124 7 10 136 8 11 157*/

  

Finding 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.