杨氏矩阵的查找算法

今天碰到了这一问题,考虑的是根据杨氏矩阵的性质,从左到右,从上到下都是递增排序的。因此想要找到杨氏矩阵当中是否存在某数,可以从右上角的数开始找起,即从

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值