查找某个数是否在矩阵中

    技术2026-08-14  1

    题目:

    给定一个矩阵,行和列分别按照从左到右,从上到下的顺序严格递增(例如下面这个),给定某个数k,要求检查k是否在此矩阵中。

     

    { 1,  3,  7,  9, 13},{ 2,  4,  8, 10, 14},{ 5,  6,  9, 12, 15},{ 7, 12, 13, 15, 19},{11, 13, 16, 18, 25}}

     

    算法设计:

        

     

    代码:

    // M_SEARCH.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> using namespace std; #define N 5 bool SearchMatrix(int a[N][N], int k, int &xloc, int &yloc) { int i,j; for (i = 0,j = N - 1;(i < N) && (j >=0);) { if (a[i][j] > k) j--; else if(a[i][j] < k) i++; else { xloc = i; yloc = j; return true; } } return false; } int _tmain(int argc, _TCHAR* argv[]) { int a[N][N] = { { 1, 3, 7, 9, 13}, { 2, 4, 8, 10, 14}, { 5, 6, 9, 12, 15}, { 7, 12, 13, 15, 19}, {11, 13, 16, 18, 25}}; int x = 0, y = 0; int k; cout << "矩阵为:" << endl; for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) cout << a[i][j] << " "; cout << endl; } cout << "Please input k: " ; cin >> k; bool answer = SearchMatrix(a, k, x, y); if (answer) { cout << "k 的位置为" << x << ","<< y << endl; } else { cout << "此矩阵中没有k!" <<endl; } return 0; }

     

    最新回复(0)