二维数组螺旋遍历
#include <iostream> using namespace std; int main() { int m,n; int left=0,right=0,top=0,bottom=0; cin>>m>>n; char array[m][n]; for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { cin>>array[i][j]; } } right=1; int i=0,j=0; for(int tst=0;tst<m*n;tst++) { if(right==1) { if(array[i][j]=='?'||j==n-1) { if(array[i][j]!='?') cout<<array[i][j]; right=0; bottom=1; i++; continue; } cout<<array[i][j]; array[i][j]='?'; j++; } else if(left==1) { if(array[i][j]=='?'||i==0) { if(array[i][j]!='?') cout<<array[i][j]; left=0; top=1; i--; continue; } cout<<array[i][j]; array[i][j]='?'; j--; } else if(top==1) { if(array[i][j]=='?'||j==0) { if(array[i][j]!='?') cout<<array[i][j]; right=1; top=0; j++; continue; } cout<<array[i][j]; array[i][j]='?'; i--; } else if(bottom==1) { if(array[i][j]=='?'||i==m-1) { if(array[i][j]!='?') cout<<array[i][j]; bottom=0; left=1; j--; continue; } cout<<array[i][j]; array[i][j]='?'; i++; } } return 0; }
有更简单的做法