蓝桥杯--算法提高 扫雷(java)

资源限制
时间限制:1.0s 内存限制:256.0MB
问题描述
  扫雷游戏你一定玩过吧!现在给你若干个n×m的地雷阵,请你计算出每个矩阵中每个单元格相邻单元格内地雷的个数,每个单元格最多有8个相邻的单元格。 0<n,m<=100
输入格式
  输入包含若干个矩阵,对于每个矩阵,第一行包含两个整数n和m,分别表示这个矩阵的行数和列数。接下来n行每行包含m个字符。安全区域用‘.’表示,有地雷区域用’*‘表示。当n=m=0时输入结束。
输出格式
  对于第i个矩阵,首先在单独的一行里打印序号:“Field #i:”,接下来的n行中,读入的’.'应被该位置周围的地雷数所代替。输出的每两个矩阵必须用一个空行隔开。

/**
样例输入
4 4
*...
....
.*..
....
3 5
**...
.....
.*...
0 0
样例输出
Field #1:
*100
2210
1*10
1110

Field #2:
**100
33200
1*100
(注意两个矩阵之间应该有一个空行,由于oj的格式化这里不能显示出来)
数据规模和约定
  0<n,m<=100
 */

——————————————————————————————————————————————

import java.util.Scanner;

public class Main {
	static int n;
	static int m;
	static char[][] g;
	static int[] dx = {-1, 1, 0, 0, -1, -1, 1, 1};
	static int[] dy = {0, 0, -1, 1, -1, 1, -1, 1};
	static int t = 1;
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while(true) {
			n = sc.nextInt();
			m = sc.nextInt();
			if(m == 0 && n == 0) break;
			g = new char[n + 5][m + 5];
			for(int i = 1;i <= n;i++) {
				String str = sc.next();
				for(int j = 1;j <= m;j++) {
					g[i][j] = str.charAt(j - 1);
				}
			}
			//输出
			System.out.println("Field #" + t + ":");
			t++;
			for(int i = 1;i <= n;i++) {
				for(int j = 1;j <= m;j++) {
					char c = g[i][j];
					if(c == '*') {
						System.out.print(c);
					}else {
						int cnt = query(i, j);
						System.out.print(cnt);
					}
				}
				System.out.println();
			}
			System.out.println();
		}
		sc.close();
	}

	private static int query(int x, int y) {
		int res = 0;
		for(int i = 0;i < 8;i++) {
			int nx = x + dx[i];
			int ny = y + dy[i];
			if(g[nx][ny] == '*') res++;
		}
		return res;
	}
}
发布了177 篇原创文章 · 获赞 15 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/QinLaoDeMaChu/article/details/105666712