1321:棋盘问题
#include<cstring>
#include<iostream>
using namespace std;
int a[10],n,k,first;
int sum;
char map[10][10];
//行由x控制,列由for循环里面的j控制
void dfs(int x,int step){int j;if(step==0){ //满足临界条件,即已经遍历完毕 sum++; //拜访种类+1 return;}if(x>=n) return; //“超出范围”只能是行超出范围,因为列控制由j负责for(j=0;j<n;j++){if(!a[j]&&map[x][j]=='#'){a[j]=1; //表示访问过该列 dfs(x+1,step-1);a[j]=0; //dfs需要回溯尝试所有情况 } }dfs(x+1,step);
}
int main(){int i,j;while(cin>>n>>k&&n!=-1&&k!=-1){ memset(a,0,sizeof(a)); //初始化摆放方案记录值、列标记sum=0;for(i=0;i<n;i++)cin>>map[i]; //二维数组当一维来进行操作(妙啊) dfs(0,k); //起始坐标为(0,0) cout<<sum<<endl;}return 0;
}
C:岛屿周长(matrix)
#include<iostream>
using namespace std;
int main(){int n, m,ans=0;int a[103][103] = {0};//二维矩阵存储cin >> n >> m;for (int i = 0; i < n; i++)for (int j = 0; j < m; j++) cin >> a[i][j];for (int i = 0; i < n; i++)//处理每一个数值为1的点,相邻如果不同,则结果加1{for (int j = 0; j < m; j++){if (a[i][j] == 0) { continue; }if (a[i - 1][j] == 0) { ans++; }if (a[i + 1][j] == 0) { ans++; }if (a[i][j - 1] == 0) { ans++; }if (a[i][j + 1] == 0) { ans++; }}}cout << ans;system("pause");return 0;
}
#include <stdio.h>
#include <string.h>
const int MAXN=110;int mapp[MAXN][MAXN];
int vis[MAXN][MAXN];
int dir[4][2]={0,1,1,0,0,-1,-1,0};
int n,m,cnt=0;int dfs(int ni,int nj){if(vis[ni][nj]==1){return 0;}if(vis[ni][nj]==0&&mapp[ni][nj]==1){vis[ni][nj]=1;}if(mapp[ni][nj]==0){return 1;}for(int i=0;i<4;i++){int ti=ni+dir[i][0];int tj=nj+dir[i][1];cnt+=dfs(ti,tj);}return 0;
}int main()
{memset(vis,0,sizeof(vis));memset(mapp,0,sizeof(mapp));scanf("%d %d",&n,&m);for(int i=1;i<=n;i++){for(int j=1;j<=m;j++){scanf("%d",&mapp[i][j]);}}for(int i=1;i<=n;i++){for(int j=1;j<=m;j++){dfs(i,j);}}printf("%d",cnt);return 0;
}
就很妙啊,周长的区域是指和0相邻的位置!!