深度优先搜索

来源:互联网 发布:手机淘宝突然打不开 编辑:程序博客网 时间:2024/06/06 05:17

1) 回文数分割:

例如:s = "aab", 分割结果为:{["aa", "b"], ["a", "a", "b"]}


bool ispalindrome(string s){if(s.size() < 2)return true;bool result = true;for(int i = 0 ; i < s.size()/2; i++){if(s[i] != s[s.size()-i-1]){result = false;break;}}return result; }void dfs(string s, int pos, vector<string>&path, vector<vector<string>>&result){if(pos == s.size()){result.push_back(path);return;}int i;for(i = pos; i < s.size();i++){string substring = s.substr(pos,i-pos+1);if(ispalindrome(substring)){path.push_back(substring);dfs(s,i+1,path,result);path.pop_back();}}}void palindpartition(string s){vector<string> path;vector<vector<string>> result;dfs(s,0,path,result);// print the resultcout<<"the palindrome partitionresult for string: " << s.c_str()<<" is as follows:"<<endl;for(int i = 0; i < result.size(); i++){cout << "[ ";for(int j = 0; j < result[i].size(); j++){cout <<"\""<< result[i][j].c_str()<<"\" "; }cout << " ]"<<endl;}}

2) restore IP address

Given a string: "25525511135";

return: ["255.255.11.135", " 255.255.111.35"];

#include "stdafx.h"#include<iostream> #include<vector>#include<map>#include<algorithm>#include<string>using namespace std;bool isvalid(string s){int result = 0;for(int i = 0; i < s.size(); i++){result = result * 10 + s[i]-'0';}if(result >= 0 && result <= 255)return true;elsereturn false;}void dfs(string s, int curpos, int num, string &path, vector<string> &result){   int length = s.size();   if(num < 0 || length-curpos > 3* num || length-curpos < num)   return;   if(num == 0 && curpos == s.size())   {   path.resize(path.size()-1);   result.push_back(path);   return;   }   for(int i = curpos; i < length; i++)   {   string tmps = s.substr(curpos,i-curpos+1);   if(isvalid(tmps))   {   dfs(s,i+1,num-1,path + tmps+'.',result);   }   }}void restoreIP(string s){string path = "";vector<string> result;dfs(s,0,4,path,result);cout << "The orginal string is:\n" <<s<<endl;cout << "The restored IP addresses are: " << endl;for(int i = 0; i < result.size(); i++){cout << result[i] << endl;}return;}int main(){string s = "25525511135";restoreIP(s);system("pause");return 0;}

3) Combination Sum:

给定集合C和目标数T, 找到C中所有的组合,相加为T,C中的数字可以重复利用。

约束: C中所有的数字为正数;所得的解无重复

例如,C = [2,3,6,7], T = [7]:

返回结果为:

[7], [2,2,3]

// OOD.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include<iostream> #include<vector>#include<map>#include<algorithm>#include<string>using namespace std;void dfs(int target, int pos, vector<int> &C, vector<int> &path, vector<vector<int>> &result){if(target < 0 || pos > C.size())return;if(target == 0){result.push_back(path);return;}for(int i = pos; i < C.size(); i++){path.push_back(C[i]);dfs(target-C[i],i,C,path, result);path.pop_back();}}void combinationSum(vector<int> C, int target){vector<int> path;vector<vector<int>> result;sort(C.begin(),C.end());dfs(target,0,C,path,result);for(int i = 0; i < result.size(); i++){cout << "[ ";for(int j = 0; j < result[i].size(); j++)cout << result[i][j] << " ";cout << "]"<<endl;}return;}int main(){int a[] = {10,1,2,7,6,1,5};vector<int> C;C.assign(a,a+sizeof(a)/sizeof(int));int target = 8;combinationSum(C,target);system("pause");return 0;}

4) 4色问题:

描述
给定N(N <= 8) 个点的地图,以及地图上各点的相邻关系,请输出用4 种颜色将地图涂色的所有方案数(要求相邻两点不能涂成相同的颜色)。数据中0 代表不相邻,1 代表相邻。

输入
第一行一个整数N,代表地图上有N 个点。
接下来N 行,每行N 个整数,每个整数是0 或者1。第i 行第j 列的值代表了第i 个点和第j 个
点之间是相邻的还是不相邻,相邻就是1,不相邻就是0。我们保证a[i][j] = a[j][i]。

输出
染色的方案数


// OOD.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include<iostream> #include<vector>#include<map>#include<algorithm>#include<string>using namespace std;#define colorNum 4bool isvalid(vector<int> &path, int pos, vector<vector<int>>&Map){vector<int> tmp = Map[pos];for(int i = 0; i < pos; i++){if(tmp[i] == 1){if(path[i] == path[pos]){return false;}}}return true;}void dfs(int pos,vector<vector<int>>&Map,vector<int> &path, vector<vector<int>> &result){if(pos == path.size()){result.push_back(path);return;}for(int i = 0; i < colorNum; i++){int tmpint = path[pos];path[pos] = i;if(!isvalid(path,pos,Map)){continue;}else{dfs(pos+1,Map,path,result);path[pos] = tmpint;}}}void fourcolor(vector<vector<int>> &Map){vector<int> path(Map[0].size(),0);vector<vector<int>> result;dfs(0,Map,path,result);cout << "there are total " << result.size() << " ways for " << colorNum <<" Problems!!"<<endl;return;}int main(){int a[8][8]={   0, 0, 0, 1, 0, 0, 1, 0,0, 0, 0, 0, 0, 1, 0, 1,0, 0, 0, 0, 0, 0, 1, 0,1, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 1, 0, 0, 0, 0, 0, 0,1, 0, 1, 0, 0, 0, 0, 0,0, 1, 0, 0, 0, 0, 0, 0};vector<vector<int>> M(8,vector<int>(8,0));for(int i = 0; i < 8; i++){M[i].assign(a[i],a[i]+8);}fourcolor(M);system("pause");return 0;}


5) sudoku solver:

write a program to solve a sudoku puzzle by filling the empty cells. empty cells are "." 

we may assume that there will be only one unique solution.


// OOD.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include<iostream> #include<vector>#include<map>#include<algorithm>#include<string>using namespace std;bool isvalid(vector<vector<char>> &board, int x, int y){for(int i = 0; i < 9; i++){if((i!=y && board[x][i] == board[x][y]) || (i!= x && board[i][y] == board[x][y]))return false;}int rowstart = x/3 * 3;int colstart = y/3 * 3;for(int i = rowstart; i < rowstart+3; i++)for(int j = colstart; j < colstart+3; j++){if(i!= x && j!= y && board[i][j] == board[x][y])return false;}return true;}bool dfs(vector<vector<char>> &board){for(int i = 0; i < board.size(); i++)for(int j = 0; j < board[0].size(); j++){if(board[i][j] == '.'){for(int k = 1; k <= 9; k++){board[i][j] = k + '0';if(isvalid(board,i,j) && dfs(board))return true;board[i][j] = '.';}return false;}}return true;}void sodo(vector<vector<char>> &board){int i,j;cout<<"original input board is: " << endl<<endl;for(i = 0; i < board.size(); i++){for(j = 0; j < board[i].size(); j++)cout<<board[i][j]<<" ";cout<<endl;}    cout<<endl<<endl;dfs(board);    cout<<"after calculate: "<< endl<<endl;for(i = 0; i < board.size(); i++){for(j = 0; j < board[i].size(); j++)cout<<board[i][j]<<" ";cout<<endl;}cout<<endl<<endl;return;   }int main(){char a[9][9]={ '5', '3', '.','.', '7', '.', '.', '.','.',    '6', '.', '.','1', '9', '5', '.', '.','.','.', '9', '8','.', '.', '.', '.', '6','.','8', '.', '.','.', '6', '.', '.', '.','3','4', '.', '.','8', '.', '3', '.', '.','1','7', '.', '.','.', '2', '.', '.', '.','6','.', '6', '.','.', '.', '.', '2', '8','.','.', '.', '.','4', '1', '9', '.', '.','5','.', '.', '.','.', '8', '.', '.', '7','9'};int Number = 9;vector<vector<char>> M(Number,vector<char>(Number,0));for(int i = 0; i < Number; i++){M[i].assign(a[i],a[i]+Number);}sodo(M);system("pause");return 0;}

6) word search:

描述:
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighbouring. The same letter cell may not be used more than once.

输入:
For example, Given board =
[
["ABCE"],
["SFCS"],
["ADEE"]
]

输出:
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.


#include "stdafx.h"#include <iostream>#include<stack>#include<string>#include<vector>#include<queue>#include<map>#include<set>using namespace std;bool dfs(int x, int y, int wordpos, string testword, vector<vector<char>>&board, vector<vector<bool>>&visited){if(wordpos == testword.size())return true;if(x >= board.size() || y >= board[0].size() || x <0 || y < 0)return false;if(board[x][y] != testword[wordpos] || visited[x][y])return false;if(board[x][y] == testword[wordpos]){visited[x][y] = true;if( dfs(x+1,y,wordpos+1,testword,board,visited)||dfs(x,y+1,wordpos+1,testword,board,visited)||dfs(x-1,y,wordpos+1,testword,board,visited)||dfs(x,y-1,wordpos+1,testword,board,visited))return true;visited[x][y] = false;}return false;}bool issubstring(string testword, vector<vector<char>> &board){int height = board.size();int width = board[0].size();vector<vector<bool>> visited(height,vector<bool>(width,false));for(int i = 0; i < board.size(); i++)for(int j = 0; j < board[i].size(); j++){if(dfs(i,j,0,testword,board,visited))return true;}return false;}int main(){vector<vector<char>> board(3,vector<char>(4));string testword;char matrix[3][4] = {{'A','B','C','E'},{'S','F','C','S'},{'A','D','E','E'}};for(int i = 0; i < sizeof(matrix)/sizeof(matrix[0]); i++){board[i].assign(matrix[i],matrix[i] + sizeof(matrix[i])/sizeof(char));}cout << "The original board is   " << endl;for(int i = 0; i < board.size(); i++){cout << "[ ";for(int j = 0; j < board[i].size(); j++)cout << board[i][j] << " ";cout << "] "<<endl;}testword = "ABCB";if(issubstring(testword, board))cout<< testword <<" is the substring in the board!!" << endl;elsecout << testword << " is NOT the substring in the board!!"<<endl;system("pause");return 0;}


0 0
原创粉丝点击