判断数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中存储矩阵。

转载于:https://www.cnblogs.com/moren/p/3662191.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值