練習
d626: 小畫家真好用
https://zerojudge.tw/ShowProblem?problemid=d626
#include <bits/stdc++.h>
using namespace std;
int n=0;
char a[101][101];
void dfs(int x,int y)
{
//此格子在地圖的範圍內,而且還沒有被上色
if(x>=0&&y>=0&&x<=n&&y<=n&&a[x][y]=='-')
{
a[x][y]='+'; //上色
dfs(x,y+1); //往下方探索 ↓
dfs(x,y-1); //往上方探索 ↑
dfs(x+1,y); //往右方探索 →
dfs(x-1,y); //往左方探索 ←
}
}
int main()
{
int x,y;
cin>>n;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
cin>>a[i][j];//輸入圖畫
cin>>x>>y; //輸入倒油漆的位置
dfs(x,y);//開始用油漆桶上色
for(int i=0;i<n;i++){
for(int j=0;j<=n;j++){
cout<<a[i][j];//輸出已經塗色的圖畫
}
cout<<endl;
}
return 0;
}
Uva 11332 - Summing Digits
#include <iostream>
using namespace std;
int f(int a)
{
int sum=0;
while(a!=0)
{
sum+=a%10;
a/=10;
}
return sum;
}
int main()
{
int x;
while(cin>>x)
{
if(x==0){break;}
while(f(x)>=10) { x=f(x); }
cout<<f(x)<<endl;
}
return 0;
}
a044: 空間切割
#include<iostream>
using namespace std;
int extraCut(int n)
{
if(n==1){
return 2;
}else{
return extraCut(n-1)+n;
}
}
int cut(int n)
{
if(n==1){
return 2;
}
else{
return cut(n-1)+extraCut(n-1);
}
}
int main(void)
{
int n;
while(cin>>n){
cout << cut(n) << endl ;
}
return 0;
}
d619: 奇摩知識
https://zerojudge.tw/ShowProblem?problemid=d619
要先知道什麼是二進位,例如9可以轉成1001
題目的意思就是假如當你輸入4的時候,1~4這些數字都要被轉成2進位
1 → 1
2 → 10
3 → 11
4 → 100
把這些轉出來的二進位數字的1加總,就會得出5,而5就是我們要的答案
第一步就是試著用遞迴將10進位轉成2進位
#include <iostream>
using namespace std;
int convertToBinary(int n)
{
if (n / 2 != 0) {
return n % 2 + convertToBinary(n / 2);
}
else{
return 1;
}
}
int main()
{
int n, sum = 0;
cin >> n;
for (int i = 1; i <= n ; i++){
sum += convertToBinary(i);
}
cout<<sum;
}