螺旋矩阵实现

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;

int a[1005][1005];
int n, m;
int r, c;
typedef struct{
	int i, j;
	int cur;
	int dir;	//1→2↓3←4↑ 
}node;
queue<node> q;
void bfs(){
	while (q.size()){
		q.pop();
	}
	node t;
	t.i=1, t.j=1;
	t.cur=1;
	t.dir=1;
	a[1][1]=1;
	q.push(t);
	while (q.size()){
		t = q.front();
		q.pop();
		if (t.cur==n*m){
			continue;
		}
		if (t.dir==1){
			if (a[t.i][t.j+1]==0 && t.j+1<=m){
				node tt;
				tt.i=t.i, tt.j=t.j+1;
				tt.cur=t.cur+1;
				tt.dir=t.dir;
				a[tt.i][tt.j]=tt.cur;
				q.push(tt);
			}else{
				node tt;
				tt.i=t.i+1;
				tt.j=t.j;
				tt.cur=t.cur+1;
				tt.dir=2;
				a[tt.i][tt.j]=tt.cur;
				q.push(tt);
			}
		}else if (t.dir==2){
			if (a[t.i+1][t.j]==0 && t.i+1<=n){
				node tt;
				tt.i=t.i+1, tt.j=t.j;
				tt.cur=t.cur+1;
				tt.dir=t.dir;
				a[tt.i][tt.j]=tt.cur;
				q.push(tt); 
			}else{
				node tt;
				tt.i=t.i, tt.j=t.j-1;
				tt.cur=t.cur+1;
				tt.dir=3;
				a[tt.i][tt.j]=tt.cur;
				q.push(tt);
			}
		}else if (t.dir==3){
			if (a[t.i][t.j-1]==0 && t.j-1>=1){
				node tt;
				tt.i=t.i, tt.j=t.j-1;
				tt.cur=t.cur+1;
				tt.dir=3;
				a[tt.i][tt.j]=tt.cur;
				q.push(tt); 
			}else{
				node tt;
				tt.i=t.i-1, tt.j=t.j;
				tt.cur=t.cur+1;
				tt.dir=4;
				a[tt.i][tt.j]=tt.cur;
				q.push(tt);
			}
		}else if (t.dir==4){
			if (a[t.i-1][t.j]==0 && t.i-1>=1){
				node tt;
				tt.i=t.i-1, tt.j=t.j;
				tt.cur=t.cur+1;
				tt.dir=4;
				a[tt.i][tt.j]=tt.cur;
				q.push(tt);
			}else{
				node tt;
				tt.i=t.i;
				tt.j=t.j+1;
				tt.cur=t.cur+1;
				tt.dir=1;
				a[tt.i][tt.j]=tt.cur;
				q.push(tt);
			}
		}
	}
}
int main(){
	scanf("%d%d", &n, &m);
	//scanf("%d%d", &r, &c);
	memset(a, 0, sizeof(a));
	bfs();
	for (int i=1; i<=n; i++){
		for (int j=1; j<=m; j++){
			printf("%d ", a[i][j]);
		}
		printf("\n");
	}
	//printf("%d", a[r][c]);
	return 0;
}
#include <iostream>
#include <cstring>
using namespace std;
int store[1005][1005];
int main() {
    // n为行数,m列数
    // r为输出的行,c为输出的列
    int n, m;
    cin>>n>>m;
    
    // 所有置为0
    memset(store,0, sizeof(store));
    // 总数
    int sum = n * m;
    int row = 0, col = 0, cnt = 1;
    store[row][col] = 1;
    while(cnt < sum)
    {
        // 向右走,直到走到头或者下一个已经走过
        while(col + 1 < m && !store[row][col+1])
            store[row][++col] = ++cnt;
        // 向下走,直到走到头或者下一个已经走过
        while(row + 1 < n && !store[row+1][col])
            store[++row][col] = ++cnt;
        // 向左走,直到走到头或者下一个已经走过
        while(col - 1 >= 0 && !store[row][col-1])
            store[row][--col] = ++cnt;
        // 向上走,直到走到头或者下一个已经走过
        while(row - 1 >= 0 && !store[row-1][col])
            store[--row][col] = ++cnt;
    }
    for (int i=0; i<n; i++){
    	for (int j=0; j<=m; j++){
    		printf("%3d", store[i][j]);
		}
		printf("\n"); 
	}
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42172261/article/details/105610895