开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 26 天,点击查看活动详情
分析
今天是我最不会的dfs,然后第一题这个板子题我TM写了半天差点没过,总之就是对每个点dfs上下左右,其实bfs据说也是可以的,记好不要st数组,因为可以走重复的点。
给定一个 n×m�×� 的二维矩阵,其中的每个元素都是一个 [1,9][1,9] 之间的正整数。
从矩阵中的任意位置出发,每次可以沿上下左右四个方向前进一步,走过的位置可以重复走。
走了 k� 次后,经过的元素会构成一个 (k+1)(�+1) 位数。
请求出一共可以走出多少个不同的 (k+1)(�+1) 位数。
输入格式
第一行包含三个整数 n,m,k�,�,�。
接下来 n� 行,每行包含 m� 个空格隔开的整数,表示给定矩阵。
输出格式
输出一个整数,表示可以走出的不同 (k+1)(�+1) 位数的个数。
数据范围
对于 30%30% 的数据, 1≤n,m≤2,0≤k≤21≤�,�≤2,0≤�≤2
对于 100%100% 的数据,1≤n,m≤5,0≤k≤5,m×n>11≤�,�≤5,0≤�≤5,�×�>1
输入样例:
3 3 2
1 1 1
1 1 1
2 1 1
输出样例:
5
样例解释
一共有 55 种可能的 33 位数:
111
112
121
211
212
难度:简单 |
---|
时/空限制:1s / 64MB |
总通过数:1888 |
总尝试数:2820 |
来源:贝壳找房2021,笔试题 |
算法标签 |
挑战模式
代码
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <vector>
#include <map>
#include <set>
#include <iomanip>
#include <cmath>
#include <unordered_map>
#include <stack>
#include <queue>
#define ll long long
#define lowbit(x) x&(-x)
using namespace std;
typedef pair<int,int> PII;
typedef pair<string,int> PSI;
typedef stack<int> stk;
int gcd(int x,int y){return y?gcd(y,x%y):x;}
bool st[10][10];
int a[10][10];
ll qmi(ll x,ll y,int mod){
ll res=1;
while(y){if(y&1) res=res*x%mod;y>>=1;x=x*x%mod;}
return res;
}
int n,m,k,cnt=0;
int ans;
map<int,int> mp;
int dx[4]={1,-1,0,0};
int dy[4]={0,0,1,-1};
inline void dfs(int x,int y,int u){
if(u==k+1){
if(!mp.count(ans)){
cnt++;
mp[ans]++;
}
return;
}
for(int i=0;i<4;i++){
int nex=x+dx[i],ney=y+dy[i];
if(nex>=1 && nex<=n && ney>=1 && ney<=m && !st[nex][ney]){
ans=ans*10+a[nex][ney];
dfs(nex,ney,u+1);
ans/=10;
}
}
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
mp.clear();
memset(st,false,sizeof st);
cin>>n>>m>>k;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin>>a[i][j];
}
}
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
memset(st,false,sizeof st);
ans=a[i][j];
dfs(i,j,1);
}
}
cout<<cnt<<"\n";
return 0;
}