在二维数组中查找

题目: 在一个二维数组中,每一行都按照从左到右的递增顺序,每一列都按照从上到下的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

1 2 8    9
2 4 9   12
4 7 10 13
6 8 11 15

#include<iostream>
#include<iomanip>
#include<list>
#include<cmath>
#include<vector>
#include<assert.h>
#include"Test.h"


bool findMatrix(int **p,int m,int n,int x)
{
    assert(p!=NULL);
    while(m>=1&&n>=1)
    {
        if(p[0][n-1]>x)
            n--;
        else if(p[0][n-1]<x)
        {
            p++;
            m--;
        }
        else
        {
            cout<<"Find"<<endl;
            return true;
        }
    }
    return false;
}
void Test()
{
    int **s;
    s=new int*[4];
    int i=0;
    for(int i=0;i<4;i++)
    {
        s[i]=new int[4];
    }
    int j;
    for(i=0;i<4;i++)
        for(j=0;j<4;j++)
        {
            cin>>s[i][j];
        }
        int find[7]={1,9,6,7,15,-8,25};
        for(i=0;i<7;i++)
        {
            cout<<"find: "<<find[i]<<"    "<<findMatrix(s,4,4,find[i])<<endl;
        }

}
void main()
{ 
    Test();
    system("pause");
}

这里包含了代码和测试用例。

原文地址:https://www.cnblogs.com/dyc0113/p/3205640.html