Yong式矩阵的查找

来源:互联网 发布:java 数组切片 编辑:程序博客网 时间:2024/04/30 08:13

问题定义:

Q:给定一个矩阵,每行和每列都是有序的(单独看每行或者每列,自左到右或自上而下看,都是递增序列).写一个算法,找到指定的元素.

这个题目好像很火的样子.

代码示例:

#include <iostream>using namespace std;const int M = 4;const int N = 4;bool find(int *matrix, int rows, int columns, int number){bool found = false;int row = 0;int column = columns - 1;while (row < rows && column >= 0){int temp = matrix[row * columns + column];if (temp == number){found = true;break;}else if (temp > number){column--;}else{row++;}}return found;}int main(int argc, char* argv[]){int data[M][N] = {{1, 2, 8, 9}, {2, 4, 9, 12},{4, 7, 10, 13},{6, 8, 11, 15}};int test[4] = {0, 6, 14, 17};int r = M;int c = N;for ( int i = 0; i < 4; i++ ){if (find((int*)data, r, c, test[i])){cout << test[i] << " found" << endl;}else{cout << test[i] << " not found" << endl;}}return 0;}