img #图解 img #代码 ##java代码实现
import java.util.Scanner;
public class Main{
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt(),m=sc.nextInt();
        int[][] q=new int[n][m];
        //偏移量
        int[] dx={-1,0,1,0};
        int[] dy={0,1,0,-1};
        //初始化条件,d=1代表往右走
        int x=0,y=0,d=1;
        for(int i=1;i<=n*m;i++){
            q[x][y]=i;
            int a=x+dx[d],b=y+dy[d];//开始挪动
            if(a<0||a>=n||b<0||b>=m||q[a][b]!=0)//判断神魔时候撞墙,一种是出借,另一种是到了原来填过的位置
            {
                d=(d+1)%4;
                a=x+dx[d];
                b=y+dy[d];
            }
            x=a;
            y=b;
        }
        for(int[] res:q){
            for(int val:res){
                System.out.printf("%d ",val);
            }
            System.out.println();
        }
    }
}

c++代码实现

#include<iostream>
using namespace std;
const int N = 110;
int q[N][N];
int n, m;
int main()
{
	cin >> n >> m;
	int dx[] = { -1,0,1,0 }, dy[] = { 0,1,0,-1 };
	int x = 0, y = 0, d = 1;
	for (int i = 1; i <= n * m; i++)
	{
		q[x][y] = i;
		int a = x + dx[d], b = y + dy[d];
		if (a < 0 || a >= n || b < 0 || b >= m || q[a][b]) {
			d = (d + 1) % 4;
			a = x + dx[d] , b = y + dy[d];
		}
		x = a , y = b;
	}
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			cout << q[i][j] << " ";
		}
		cout << endl;
	}
	return 0;
}
posted on 2023-05-08 08:44  许七安gyg  阅读(31)  评论(0编辑  收藏  举报
$(document).ready(function() { // 禁止右键 $(document).bind("contextmenu", function(){return false;}); // 禁止选择 $(document).bind("selectstart", function(){return false;}); // 禁止Ctrl+C 和Ctrl+A $(document).keydown(function(event) { if ((event.ctrlKey&&event.which==67) || (event.ctrlKey&&event.which==86)) { //alert("对不起,版权所有,禁止复制"); return false; } }); });