1 条题解

  • 0
    @ 2023-6-11 12:19:06

    C :

    #include<stdio.h>
    int a[10][10],n,m;
    void dfs(int i,int j,int k){
    	if(i<1||i>n||j<1||j>m||a[i][j]!=0) return;
    	a[i][j] = k;
    	//四方向
    	dfs(i,j+1,k+1);
    	dfs(i+1,j,k+1); 
    	dfs(i,j-1,k+1);
    	dfs(i-1,j,k+1);
    }
    int main(){
       scanf("%d%d",&n,&m);
       int i,j;
       dfs(1,1,1);
       for(i=1;i<=n;i++){
       	   for(j=1;j<=m;j++){
       			printf("%3d",a[i][j]);
    	   }
    	   printf("\n");
       } 
        return 0;
    }
    
    

    C++ :

    #include<bits/stdc++.h>
    using namespace std;
    int a[100][100],n,m;
    
    //x y表示要填充的下标,k表示要填充的值 
    void fun(int x,int y,int k){
    	a[x][y] = k;
    	//按照顺时针:右、下、左、上,分别探测四个方向
    	//向右探测:右侧那个格子没有填值,且没有出方阵
    	if(a[x][y+1] == 0 && y+1<=m) fun(x,y+1,k+1); 
    	if(a[x+1][y] == 0 && x+1<=n) fun(x+1,y,k+1);
    	if(a[x][y-1] == 0 && y-1>=1) fun(x,y-1,k+1);
    	if(a[x-1][y] == 0 && x-1>=1) fun(x-1,y,k+1);
    } 
    
    int main(){
    	int i,j;
        cin>>n>>m;
        //从1,1点开始,填充1 
        fun(1,1,1); 
        
        //打印
    	for(i = 1;i <= n;i++){
    		for(j = 1;j <= m;j++){
    			cout<<setw(3)<<a[i][j];
    		}
    		cout<<endl;
    	} 
    }
    
    

    Java :

    
    import java.util.Scanner;
    
    public class Main {
    	static int a[][] = new int[10][10];
    	static int n;
    	static int m;
    	// 优先向右, 向下, 向左,向上
    	static void dfs(int i, int j, int num) {
    		// 二维数组单元赋值
    		a[i][j] = num;
    		if ( j + 1 < m && a[i][j + 1] == 0)
    			dfs(i, j + 1, num + 1);
    		if ( i + 1 < n && a[i + 1][j] == 0)
    			dfs(i + 1, j, num + 1);
    		if (j - 1 >= 0  && a[i][j - 1] == 0)
    			dfs(i, j - 1, num + 1);
    		if (i - 1 >= 0  && a[i - 1][j] == 0)
    			dfs(i - 1, j, num + 1);
    	}
    
    	public static void main(String[] args) {
    		Scanner sc = new Scanner(System.in);
    		n = sc.nextInt();
    		m = sc.nextInt();
    	   int[][] b=new int[n][m];
    	     a=b;
    		dfs(0, 0, 1);
    		for (int i = 0; i < n; i++) {
    			for (int j = 0; j <m; j++) {
    				System.out.printf("%3d", a[i][j]);
    			}
    			System.out.println();
    		}
    		
    	}
    
    }
    

    Python :

    sr=input().split()
    n=int(sr[0])
    m=int(sr[1])
    a=[[0 for i in range(m)] for j in range(n)]
    k=1
    i=0
    j=0
    while(k<=n*m):
        a[i][j]=k
        if(j+1<m and a[i][j+1]==0):
           j=j+1
        elif(i+1<n and a[i+1][j]==0):
            i=i+1
        elif(j-1>=0 and a[i][j-1]==0):
            j=j-1
        elif(i-1>=0 and a[i-1][j]==0):
            i=i-1
        k=k+1
    for i in range(n):
        for j in range(m):
            print("%3d"%a[i][j],end="")
        print()
    
    • 1

    信息

    ID
    2499
    时间
    1000ms
    内存
    128MiB
    难度
    (无)
    标签
    递交数
    0
    已通过
    0
    上传者