• DFS-深度优先遍历


    #include <iostream>
    
    /*
    5 4
    0 0 1 0
    0 0 0 0
    0 0 1 0
    0 1 0 0
    0 0 0 1
    0 0 4 1
    
    Total: 9 7 5
    Min: 5
    --------------------------------
    Process exited with return value 0
    Press any key to continue . . .
    */
    
    using namespace std;
    
    int n, m;
    int minnum = 9999999;
    int endy1 = 0, endy2 = 0; 
    int maze[20][20] = {0}, book[20][20] = {0};
    int direction[4][2] = { {0, 1}, {1, 0}, {0, -1}, {-1, 0} };
    
    void DFS(int x, int y, int step)
    {
    	if(x == endy1 && y == endy2)
    	{
    		if(step < minnum)
    		{
    			minnum = step;
    			cout << minnum << " ";
    		}
    		
    		return;
    	}
    	
    	 for(int i = 0; i <= 3; i++)
    	 {
    	 	int tx = x + direction[i][0];
    	 	int ty = y + direction[i][1];
    	 	
    	 	if(tx < 0 || tx > n - 1 || ty < 0 || ty > m - 1)
    	 	{
    	 		continue;
    	 	}
    	 	
    	 	if(maze[tx][ty] == 0 && book[tx][ty] == 0)
    	 	{
    	 		book[tx][ty] = 1;
    	 		DFS(tx, ty, step + 1);
    	 		book[tx][ty] = 0;//尝试结束,取消这个点的标记 
    	 	}
    	 }
    	 
    	 return;
    }
    
    int main()
    {	
    	cin >> n >> m;
    	
    	for(int i = 0; i < n; i++)
    	{
    		for(int j = 0; j < m; j++)
    		{
    			cin >> maze[i][j];
    		}
    	}
    	
    	int beginx1, beginx2;
    	cin >> beginx1 >> beginx2 >> endy1 >> endy2;
    	
    	cout << endl << "Total: ";
    	DFS(beginx1, beginx2, 0);
    	
    	cout << endl << "Min: " << minnum;
    	
    	return 0;
    } 
    

      

  • 相关阅读:
    C 数组初始化
    Linux函数之snprintf()[一]
    出现一下错误
    IOS通过post方式发送图片续
    IOS通过post方式发送图片
    TCP和UDP的区别趣解
    [转]Release mode debugging with VC++
    [转]Math For Programmers
    OS:kernel and shell
    Reminder: 8020 rule
  • 原文地址:https://www.cnblogs.com/hfultrastrong/p/6372306.html
Copyright © 2020-2023  润新知