iT邦幫忙

2025 iThome 鐵人賽

DAY 27
0
自我挑戰組

cpe30天練習系列 第 27

cpe練習day27

  • 分享至 

  • xImage
  •  

今天是練習cpe的Minesweeper題目

程式碼

#include <bits/stdc++.h>
using namespace std;
char a[105][105];
int b[105][105];
int dx[] = {1,0,-1,-1,1,-1,0,1};
int dy[] = {1,1,1,0,0,-1,-1,-1};
 
int main() 
{
    int n ,m;
    int c=1;
    string s;
    while(cin >> n >> m)
    {
    	if(n == 0 && m == 0)
    	{
    		break;
		}
    	for(int i=0 ;i<n ;i++)
    	{
    		cin >> s;
    		for(int j=0 ;j<m ;j++)
			{
				a[i][j]=s[j];
			}
		}
		memset(b ,0 ,sizeof(b));
		for(int i=0 ;i<n ;i++)
		{
			for(int j=0 ;j<m ;j++)
			{
				if(a[i][j] == '*')
				{
					b[i][j] = -1;
				}
				else
				{
					for(int k=0 ;k<8 ;k++)
					{
						int x= i + dx[k];
						int y= j + dy[k];
						if(x>=0 && x<n && y>=0 && y<m && a[x][y]=='*')
						{
							b[i][j]++;
						}
					}
				} 
			}
		}
		if(c>1)
		{
			cout << endl;	
		}
		cout << "Field #" << c++ << ":" <<endl;
		for(int i=0 ;i<n ;i++)
		{
			for(int j=0 ;j<m ;j++)
			{
				if(b[i][j] == -1)
				{
					cout << '*';
				}
				else
				{
					cout << b[i][j];
				}
			}
			cout << endl;
		}
	}
	return 0;	
}

解題方向

  • int dx[] ,int dy[] -> 代表8個方向(右下、右、右上、上、下、左下、左、左上),方便掃描周圍
  • 讀入地圖
for(int i = 0; i < n; i++)
{
    cin >> s;
    for(int j = 0; j < m; j++)
    {
        a[i][j] = s[j];
    }
}
  • 計算每格地雷數
for(int i=0 ; i<n ; i++)
{
    for(int j=0 ; j<m ; j++)
    {
        if(a[i][j] == '*')
        {
            b[i][j] = -1;
        }
        else
        {
            for(int k=0 ; k<8 ; k++)
            {
                int x = i + dx[k];
                int y = j + dy[k];
                if(x>=0 && x<n && y>=0 && y<m && a[x][y]=='*')
                {
                    b[i][j]++;
                }
            }
        } 
    }
}
  • 印出地圖
for(int i=0 ; i<n ; i++)
{
    for(int j=0 ; j<m ; j++)
    {
        if(b[i][j] == -1)
            cout << '*';
        else
            cout << b[i][j];
    }
    cout << endl;
}

上一篇
cpe練習day26
下一篇
cpe練習day28
系列文
cpe30天練習28
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言