zoukankan      html  css  js  c++  java
  • 判断数X是否在矩阵中

    原题:《数据结构与算法分析C++描述(第三版)》练习2.27

    问题描述:N*N矩阵,每一行从左到右增加,每一列从上到下增加。给出O(N)最坏情形算法决定是否数X在该矩阵中。

    代码:

     1 #include<iostream>
     2 #include<vector>
     3 #include<fstream>
     4 #include<sstream>
     5 
     6 using namespace std;
     7 
     8 int searchx(vector<vector<int> > v,int x)
     9 {
    10     int i(0),j(0);
    11     i=v.size()-1;
    12     while(j<v.size()&&i>=0)
    13     {
    14         while(v[i][j]<x) j++;
    15         if(v[i][j]==x)   return 0;
    16         i--;
    17     }
    18     return -1;
    19 }
    20 
    21 int main()
    22 {
    23     fstream myfile("2.27.txt");
    24     if(!myfile)
    25     {
    26         cerr<<"error"<<endl;
    27         return -1;
    28     }
    29     string line;
    30     int word;
    31     vector<int> tv;
    32     vector<vector<int> > v;
    33     while(getline(myfile,line))
    34     {
    35         tv.clear();
    36         istringstream stream(line);
    37         while(stream>>word) tv.push_back(word);
    38         v.push_back(tv);
    39     }
    40     myfile.close();
    41     int x;
    42     cin>>x;
    43     int result = searchx(v,x);
    44     if(result==0) cout<<"find the number in matrix"<<endl;
    45     else cout<<"can not find the number in matrix"<<endl;
    46     return 0;
    47 }

     注:文件2.27.txt中存储矩阵。

  • 相关阅读:
    经典多线程问题(四)-轮流打印字母和数字
    经典多线程问题 (一)-多线程售票
    买卖股票的最佳时机 II
    最长递增(严格递增)子序列-可以不连续
    环形链表 II
    最小栈
    买卖股票的最佳时机
    二叉树的层序遍历
    字符串相加
    最大子序和
  • 原文地址:https://www.cnblogs.com/moren/p/3662191.html
Copyright © 2011-2022 走看看