day14

1.剑指 Offer 12. 矩阵中的路径

dfs

!!!这道题visited[x][y]不可以用visited[x * m + y]代替

 1 class Solution {
 2 public:
 3     int next[4][2] = {-1,0,0,1,1,0,0,-1};
 4     int visited[201][201];
 5     bool exist(vector<vector<char>>& board, string word) {
 6       int m = board.size(),n = board[0].size();
 7       int len = word.size();
 8       for(int i = 0;i < m;i ++){
 9           for(int j = 0;j < n;j ++){
10               if(board[i][j] == word[0]){
11                 visited[i][j] = 1;
12                 if(dfs(board,word,m,n,i,j,len,0))
13                   return true;
14                 visited[i][j] = 0;
15               }
16           }
17       }
18       return false;
19     }  
20 
21     bool dfs(vector<vector<char>>& board,string word,int m,int n,int x,int y,int len,int cnt){   
22       printf("%c%d ",board[x][y],cnt);
23       if(cnt == len - 1 && board[x][y] == word[cnt])  return true;
24       if(board[x][y] != word[cnt])  return false;
25       else{
26           for(int i = 0;i < 4;i ++){
27             int px = x + next[i][0],py = y + next[i][1];
28             if(px >= 0 && px < m && py >= 0 && py < n && visited[px][py] == 0){
29                 visited[px][py] = 1;
30                 if(dfs(board,word,m,n,px,py,len,cnt + 1))
31                     return true;
32                 visited[px][py] = 0;
33             }
34           }
35       }
36       return false;
37     }
38 };

 

2.剑指 Offer 13. 机器人的运动范围

 1 class Solution {
 2 public:
 3     int next[4][2]={-1,0,0,1,1,0,0,-1};
 4     int visited[101][101];
 5     
 6     int movingCount(int m, int n, int k) {
 7       if(k == 0) return 1;
 8       int cnt = 0;
 9       dfs(m,n,k,0,0);
10       for(int i = 0;i < m;i ++)
11        for(int j = 0;j < n;j ++)
12         if(visited[i][j] == 1)  cnt ++;
13       return cnt;
14     }
15 
16     void dfs(int m,int n,int k,int x,int y){
17       if(isExceed(x,y,k)) return;
18       visited[x][y] = 1;
19       for(int i = 0;i < 4;i ++){
20           int px = x + next[i][0],py = y + next[i][1];
21           if(px >= 0 && px < m && py >= 0 && py < n && visited[px][py] == 0)
22               dfs(m,n,k,px,py);
23        }
24     }
25 
26     bool isExceed(int p,int q,int k){
27         int tmp = 0;
28         while(p){
29           tmp += p % 10;
30           p /= 10;
31         }
32         while(q){
33           tmp += q % 10;
34           q /= 10;
35         }
36         if(tmp > k) return true;
37         return false;
38     }
39 };

 

posted @ 2022-07-10 22:37  balabalahhh  阅读(19)  评论(0)    收藏  举报