今天碰到了这一问题,考虑的是根据杨氏矩阵的性质,从左到右,从上到下都是递增排序的。因此想要找到杨氏矩阵当中是否存在某数,可以从右上角的数开始找起,即从
Y_Matrix[0][columns-1]开始找起。此时如果Y_Matrix[0][columns-1]比要找的数大,则继续往左查找,即columns-2;若此时比要找的数小,那么就要往下开始找起,即比较
Y_Matrix[1][columns-1]与要找的数比较,当相等时,及找到了,循环停止;
另外注意的是: 1二维数组(矩阵)的定义方法和格式。
2二维数组传参的方法,要用(int *)数组名,进行传参;
下面是实现代码。
// FindNumberInYoungMatrix.cpp : 定义控制台应用程序的入口点。
/*
@mishidemudong
@2015-6-12
*/
//
#include "stdafx.h"
#include<iostream>
using namespace std;
bool FindNumInYoungMatrix(int *Y_matrix, int rows, int columns, int number)
{
bool Found = false;
if (Y_matrix != NULL&&rows > 0 && columns > 0)
{
int row = 0;
int column = columns - 1;
while (row < rows&&column >= 0)
{
if (Y_matrix[row*columns + column] == number)
{
Found = true;
break;
}
if (Y_matrix[row*columns + column] > number)
--column;
else
++row;
}
}
return Found;
}
int _tmain(int argc, _TCHAR* argv[])
{
int Y_matrix[4][4] = { { 1, 2, 8, 9 },{ 2, 4, 9, 12 },{4, 7, 10, 13},{ 6, 8, 11, 15} };
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j)
printf("%d ", Y_matrix[i][j]);
printf("\n");
}
for (int search = 1; search <= 15; ++search)
{
cout << search;
if (FindNumInYoungMatrix((int*)Y_matrix, 4, 4, search)) //这里的Y_matrix的传入方式还需要学习
cout << ":存在";
else
cout << ":不存在";
cout << endl;
}
return 0;
}