原題:《數據結構與算法分析C++描述(第三版)》練習2.27ios
問題描述: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中存儲矩陣。spa