螺旋矩阵(逆时针)
題目描述:給你一個正整數 n ,生成一個包含 1 到 n2 所有元素,且元素按順時針順序螺旋排列的 n x n 正方形矩陣 matrix 。
對于c語言,換成數組就可以了。
方法一:按層遍歷(這個層是一圈一圈的)
思路:
對于每層,從左上方開始以順時針的順序填入所有元素。假設當前層的左上角位于(top,left),右下角位于(bottom,right),按照如下順序填入當前層的元素。
- 從左到右填入上側元素,依次為(top,left) 到 (top,right)。
- 從上到下填入右側元素,依次為 (top+1,right) 到 (bottom,right)。
- 如果 left<right 且 top<bottom,則從右到左填入下側元素,依次為(bottom,right?1) 到(bottom,left+1),以及從下到上填入左側元素,依次為 (bottom,left) 到 (top+1,left)。
- 填完當前層的元素之后,將 left 和top 分別增加 1,將right 和 bottom 分別減少 1,進入下一層繼續填入元素,直到填完所有元素為止。
代碼:
vector<vector<int>> generateMatrix(int n) {vector<vector<int>>ans(n,vector<int>(n));int num = 1 , end = n*n;int top = 0 , botttom = n-1 , left = 0 ,right = n-1;while(num<=end){for(int col=left;col<=right;col++){ans[top][col]=num;num++;}top++;for(int row=top;row<=botttom;row++){ans[row][right]=num;num++;}right--;for(int col=right;col>=left;col--){ans[botttom][col]=num;num++;}botttom--;for(int row=botttom;row>=top;row--){ans[row][left]=num;num++;}left++;}return ans;}方法二:方向數組
思路:當下標沒有越界,且下一個值是空的,就往這個方向填數。不符合后,說明越界了,先把下標拉回來,再改變方向。
代碼:
vector<vector<int>> generateMatrix(int n) {vector<vector<int>>ans(n,vector<int>(n,0)); //初始化均為0int num = 2 , end = n*n;int dx[4]={0,1,0,-1};int dy[4] = {1,0,-1,0};int i=0, x=0,y=0;ans[0][0]=1;while(num<=end){ x+=dx[i];//往該方向移動y+=dy[i]; while(x>=0&&x<n&&y>=0&&y<n&&!ans[x][y]){ans[x][y]=num;x+=dx[i];y+=dy[i];++num;}x-=dx[i]; //越界了返回來y-=dy[i];i++;//改變方向i%=4;}return ans;}總結
- 上一篇: Python环境下的数据库编程
- 下一篇: 谭浩强课后题(数组篇)